wolfssl_server.ino 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  1. /* wolfssl_server.ino
  2. *
  3. * Copyright (C) 2006-2023 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. /*
  22. Tested with:
  23. 1) Intel Galileo acting as the Client, with a laptop acting as a server using
  24. the server example provided in examples/server.
  25. Legacy Arduino v1.86 was used to compile and program the Galileo
  26. 2) Espressif ESP32 WiFi
  27. 3) Arduino Due, Nano33 IoT, Nano RP-2040
  28. */
  29. /*
  30. * Note to code editors: the Arduino client and server examples are edited in
  31. * parallel for side-by-side comparison between examples.
  32. */
  33. /* If you have a private include, define it here, otherwise edit WiFi params */
  34. #define MY_PRIVATE_CONFIG "/workspace/my_private_config.h"
  35. /* set REPEAT_CONNECTION to a non-zero value to continually run the example. */
  36. #define REPEAT_CONNECTION 1
  37. /* Edit this with your other TLS host server address to connect to: */
  38. /* #define WOLFSSL_TLS_SERVER_HOST "192.168.1.34" */
  39. /* wolfssl TLS examples communicate on port 11111 */
  40. #define WOLFSSL_PORT 11111
  41. /* Choose a monitor serial baud rate: 9600, 14400, 19200, 57600, 74880, etc. */
  42. #define SERIAL_BAUD 115200
  43. /* We'll wait up to 2000 milliseconds to properly shut down connection */
  44. #define SHUTDOWN_DELAY_MS 2000
  45. /* Number of times to retry connection. */
  46. #define RECONNECT_ATTEMPTS 20
  47. /* Optional stress test. Define to consume memory until exhausted: */
  48. /* #define MEMORY_STRESS_TEST */
  49. /* Choose client or server example, not both. */
  50. /* #define WOLFSSL_CLIENT_EXAMPLE */
  51. #define WOLFSSL_SERVER_EXAMPLE
  52. #if defined(MY_PRIVATE_CONFIG)
  53. /* the /workspace directory may contain a private config
  54. * excluded from GitHub with items such as WiFi passwords */
  55. #include MY_PRIVATE_CONFIG
  56. static const char* ssid PROGMEM = MY_ARDUINO_WIFI_SSID;
  57. static const char* password PROGMEM = MY_ARDUINO_WIFI_PASSWORD;
  58. #else
  59. /* when using WiFi capable boards: */
  60. static const char* ssid PROGMEM = "your_SSID";
  61. static const char* password PROGMEM = "your_PASSWORD";
  62. #endif
  63. #define BROADCAST_ADDRESS "255.255.255.255"
  64. /* There's an optional 3rd party NTPClient library by Fabrice Weinberg.
  65. * If it is installed, uncomment define USE_NTP_LIB here: */
  66. /* #define USE_NTP_LIB */
  67. #ifdef USE_NTP_LIB
  68. #include <NTPClient.h>
  69. #endif
  70. #include <wolfssl.h>
  71. /* Important: make sure settings.h appears before any other wolfSSL headers */
  72. #include <wolfssl/wolfcrypt/settings.h>
  73. /* Reminder: settings.h includes user_settings.h
  74. * For ALL project wolfSSL settings, see:
  75. * [your path]/Arduino\libraries\wolfSSL\src\user_settings.h */
  76. #include <wolfssl/ssl.h>
  77. #include <wolfssl/certs_test.h>
  78. #include <wolfssl/wolfcrypt/error-crypt.h>
  79. /* Define DEBUG_WOLFSSL in user_settings.h for more verbose logging. */
  80. #if defined(DEBUG_WOLFSSL)
  81. #define PROGRESS_DOT F("")
  82. #else
  83. #define PROGRESS_DOT F(".")
  84. #endif
  85. /* Convert a macro to a string */
  86. #define xstr(x) str(x)
  87. #define str(x) #x
  88. /* optional board-specific networking includes */
  89. #if defined(ESP32)
  90. #define USING_WIFI
  91. #include <WiFi.h>
  92. #include <WiFiUdp.h>
  93. #ifdef USE_NTP_LIB
  94. WiFiUDP ntpUDP;
  95. #endif
  96. /* Ensure the F() flash macro is defined */
  97. #ifndef F
  98. #define F
  99. #endif
  100. WiFiClient client;
  101. WiFiServer server(WOLFSSL_PORT);
  102. #elif defined(ESP8266)
  103. #define USING_WIFI
  104. #include <ESP8266WiFi.h>
  105. WiFiClient client;
  106. WiFiServer server(WOLFSSL_PORT);
  107. #elif defined(ARDUINO_SAM_DUE)
  108. #include <SPI.h>
  109. /* There's no WiFi/Ethernet on the Due. Requires Ethernet Shield.
  110. /* Needs "Ethernet by Various" library to be installed. Tested with V2.0.2 */
  111. #include <Ethernet.h>
  112. EthernetClient client;
  113. EthernetClient server(WOLFSSL_PORT);
  114. #elif defined(ARDUINO_SAMD_NANO_33_IOT)
  115. #define USING_WIFI
  116. #include <SPI.h>
  117. #include <WiFiNINA.h> /* Needs Arduino WiFiNINA library installed manually */
  118. WiFiClient client;
  119. WiFiServer server(WOLFSSL_PORT);
  120. #elif defined(ARDUINO_ARCH_RP2040)
  121. #define USING_WIFI
  122. #include <SPI.h>
  123. #include <WiFiNINA.h>
  124. WiFiClient client;
  125. WiFiServer server(WOLFSSL_PORT);
  126. #elif defined(USING_WIFI)
  127. #define USING_WIFI
  128. #include <WiFi.h>
  129. #include <WiFiUdp.h>
  130. #ifdef USE_NTP_LIB
  131. WiFiUDP ntpUDP;
  132. #endif
  133. WiFiClient client;
  134. WiFiServer server(WOLFSSL_PORT);
  135. /* TODO
  136. #elif defined(OTHER_BOARD)
  137. */
  138. #else
  139. #define USING_WIFI
  140. WiFiClient client;
  141. WiFiServer server(WOLFSSL_PORT);
  142. #endif
  143. /* Only for syntax highlighters to show interesting options enabled: */
  144. #if defined(HAVE_SNI) \
  145. || defined(HAVE_MAX_FRAGMENT) \
  146. || defined(HAVE_TRUSTED_CA) \
  147. || defined(HAVE_TRUNCATED_HMAC) \
  148. || defined(HAVE_CERTIFICATE_STATUS_REQUEST) \
  149. || defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2) \
  150. || defined(HAVE_SUPPORTED_CURVES) \
  151. || defined(HAVE_ALPN) \
  152. || defined(HAVE_SESSION_TICKET) \
  153. || defined(HAVE_SECURE_RENEGOTIATION) \
  154. || defined(HAVE_SERVER_RENEGOTIATION_INFO)
  155. #endif
  156. /* we expect our IP address from DHCP */
  157. static WOLFSSL_CTX* ctx = NULL;
  158. static WOLFSSL* ssl = NULL;
  159. static char* wc_error_message = (char*)malloc(80 + 1);
  160. static char errBuf[80];
  161. #if defined(MEMORY_STRESS_TEST)
  162. #define MEMORY_STRESS_ITERATIONS 100
  163. #define MEMORY_STRESS_BLOCK_SIZE 1024
  164. #define MEMORY_STRESS_INITIAL (4*1024)
  165. static char* memory_stress[MEMORY_STRESS_ITERATIONS]; /* typically 1K per item */
  166. static int mem_ctr = 0;
  167. #endif
  168. static int EthernetSend(WOLFSSL* ssl, char* msg, int sz, void* ctx);
  169. static int EthernetReceive(WOLFSSL* ssl, char* reply, int sz, void* ctx);
  170. static int reconnect = RECONNECT_ATTEMPTS;
  171. static int lng_index PROGMEM = 0; /* 0 = English */
  172. #if defined(__arm__)
  173. #include <malloc.h>
  174. extern char _end;
  175. extern "C" char *sbrk(int i);
  176. static char *ramstart=(char *)0x20070000;
  177. static char *ramend=(char *)0x20088000;
  178. #endif
  179. /*****************************************************************************/
  180. /* fail_wait - in case of unrecoverable error */
  181. /*****************************************************************************/
  182. int fail_wait(void) {
  183. show_memory();
  184. Serial.println(F("Failed. Halt."));
  185. while (1) {
  186. delay(1000);
  187. }
  188. return 0;
  189. }
  190. /*****************************************************************************/
  191. /* show_memory() to optionally view during debugging. */
  192. /*****************************************************************************/
  193. int show_memory(void)
  194. {
  195. #if defined(__arm__)
  196. struct mallinfo mi = mallinfo();
  197. char *heapend=sbrk(0);
  198. register char * stack_ptr asm("sp");
  199. #if defined(DEBUG_WOLFSSL_VERBOSE)
  200. Serial.print(" arena=");
  201. Serial.println(mi.arena);
  202. Serial.print(" ordblks=");
  203. Serial.println(mi.ordblks);
  204. Serial.print(" uordblks=");
  205. Serial.println(mi.uordblks);
  206. Serial.print(" fordblks=");
  207. Serial.println(mi.fordblks);
  208. Serial.print(" keepcost=");
  209. Serial.println(mi.keepcost);
  210. #endif
  211. #if defined(DEBUG_WOLFSSL) || defined(MEMORY_STRESS_TEST)
  212. Serial.print("Estimated free memory: ");
  213. Serial.print(stack_ptr - heapend + mi.fordblks);
  214. Serial.println(F(" bytes"));
  215. #endif
  216. #if (0)
  217. /* Experimental: not supported on all devices: */
  218. Serial.print("RAM Start %lx\n", (unsigned long)ramstart);
  219. Serial.print("Data/Bss end %lx\n", (unsigned long)&_end);
  220. Serial.print("Heap End %lx\n", (unsigned long)heapend);
  221. Serial.print("Stack Ptr %lx\n",(unsigned long)stack_ptr);
  222. Serial.print("RAM End %lx\n", (unsigned long)ramend);
  223. Serial.print("Heap RAM Used: ",mi.uordblks);
  224. Serial.print("Program RAM Used ",&_end - ramstart);
  225. Serial.print("Stack RAM Used ",ramend - stack_ptr);
  226. Serial.print("Estimated Free RAM: %d\n\n",stack_ptr - heapend + mi.fordblks);
  227. #endif
  228. #else
  229. Serial.println(F("show_memory() not implemented for this platform"));
  230. #endif
  231. return 0;
  232. }
  233. /*****************************************************************************/
  234. /* EthernetSend() to send a message string. */
  235. /*****************************************************************************/
  236. int EthernetSend(WOLFSSL* ssl, char* message, int sz, void* ctx) {
  237. int sent = 0;
  238. (void)ssl;
  239. (void)ctx;
  240. sent = client.write((byte*)message, sz);
  241. return sent;
  242. }
  243. /*****************************************************************************/
  244. /* EthernetReceive() to receive a reply string. */
  245. /*****************************************************************************/
  246. int EthernetReceive(WOLFSSL* ssl, char* reply, int sz, void* ctx) {
  247. int ret = 0;
  248. (void)ssl;
  249. (void)ctx;
  250. while (client.available() > 0 && ret < sz) {
  251. reply[ret++] = client.read();
  252. }
  253. return ret;
  254. }
  255. /*****************************************************************************/
  256. /* Arduino setup_hardware() */
  257. /*****************************************************************************/
  258. int setup_hardware(void) {
  259. int ret = 0;
  260. #if defined(ARDUINO_SAMD_NANO_33_IOT)
  261. Serial.println(F("Detected known tested and working Arduino Nano 33 IoT"));
  262. #elif defined(ARDUINO_ARCH_RP2040)
  263. Serial.println(F("Detected known tested and working Arduino RP-2040"));
  264. #elif defined(__arm__) && defined(ID_TRNG) && defined(TRNG)
  265. /* need to manually turn on random number generator on Arduino Due, etc. */
  266. pmc_enable_periph_clk(ID_TRNG);
  267. trng_enable(TRNG);
  268. Serial.println(F("Enabled ARM TRNG"));
  269. #endif
  270. show_memory();
  271. randomSeed(analogRead(0));
  272. return ret;
  273. }
  274. /*****************************************************************************/
  275. /* Arduino setup_datetime() */
  276. /* The device needs to have a valid date within the valid range of certs. */
  277. /*****************************************************************************/
  278. int setup_datetime(void) {
  279. int ret = 0;
  280. int ntp_tries = 20;
  281. /* we need a date in the range of cert expiration */
  282. #ifdef USE_NTP_LIB
  283. #if defined(ESP32)
  284. NTPClient timeClient(ntpUDP, "pool.ntp.org");
  285. timeClient.begin();
  286. timeClient.update();
  287. delay(1000);
  288. while (!timeClient.isTimeSet() && (ntp_tries > 0)) {
  289. timeClient.forceUpdate();
  290. Serial.println(F("Waiting for NTP update"));
  291. delay(2000);
  292. ntp_tries--;
  293. }
  294. if (ntp_tries <= 0) {
  295. Serial.println(F("Warning: gave up waiting on NTP"));
  296. }
  297. Serial.println(timeClient.getFormattedTime());
  298. Serial.println(timeClient.getEpochTime());
  299. #endif
  300. #endif
  301. #if defined(ESP32)
  302. /* see esp32-hal-time.c */
  303. ntp_tries = 5;
  304. /* Replace "pool.ntp.org" with your preferred NTP server */
  305. configTime(0, 0, "pool.ntp.org");
  306. /* Wait for time to be set */
  307. while ((time(nullptr) <= 100000) && ntp_tries > 0) {
  308. Serial.println(F("Waiting for time to be set..."));
  309. delay(2000);
  310. ntp_tries--;
  311. }
  312. #endif
  313. return ret;
  314. } /* setup_datetime */
  315. /*****************************************************************************/
  316. /* Arduino setup_network() */
  317. /*****************************************************************************/
  318. int setup_network(void) {
  319. int ret = 0;
  320. #if defined(USING_WIFI)
  321. int status = WL_IDLE_STATUS;
  322. /* The ESP8266 & ESP32 support both AP and STA. We'll use STA: */
  323. #if defined(ESP8266) || defined(ESP32)
  324. WiFi.mode(WIFI_STA);
  325. #else
  326. String fv;
  327. if (WiFi.status() == WL_NO_MODULE) {
  328. Serial.println("Communication with WiFi module failed!");
  329. /* don't continue if no network */
  330. while (true) ;
  331. }
  332. fv = WiFi.firmwareVersion();
  333. if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
  334. Serial.println("Please upgrade the firmware");
  335. }
  336. #endif
  337. Serial.print(F("Connecting to WiFi "));
  338. Serial.print(ssid);
  339. status = WiFi.begin(ssid, password);
  340. while (status != WL_CONNECTED) {
  341. delay(1000);
  342. Serial.print(F("."));
  343. Serial.print(status);
  344. status = WiFi.status();
  345. }
  346. Serial.println(F(" Connected!"));
  347. #else
  348. /* Newer Ethernet shields have a
  349. * MAC address printed on a sticker on the shield */
  350. byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  351. IPAddress ip(192, 168, 1, 42);
  352. IPAddress myDns(192, 168, 1, 1);
  353. Ethernet.init(10); /* Most Arduino shields */
  354. /* Ethernet.init(5); * MKR ETH Shield */
  355. /* Ethernet.init(0); * Teensy 2.0 */
  356. /* Ethernet.init(20); * Teensy++ 2.0 */
  357. /* Ethernet.init(15); * ESP8266 with Adafruit FeatherWing Ethernet */
  358. /* Ethernet.init(33); * ESP32 with Adafruit FeatherWing Ethernet */
  359. Serial.println(F("Initialize Ethernet with DHCP:"));
  360. if (Ethernet.begin(mac) == 0) {
  361. Serial.println(F("Failed to configure Ethernet using DHCP"));
  362. /* Check for Ethernet hardware present */
  363. if (Ethernet.hardwareStatus() == EthernetNoHardware) {
  364. Serial.println(F("Ethernet shield was not found."));
  365. while (true) {
  366. delay(1); /* do nothing */
  367. }
  368. }
  369. if (Ethernet.linkStatus() == LinkOFF) {
  370. Serial.println(F("Ethernet cable is not connected."));
  371. }
  372. /* try to configure using IP address instead of DHCP : */
  373. Ethernet.begin(mac, ip, myDns);
  374. }
  375. else {
  376. Serial.print(F(" DHCP assigned IP "));
  377. Serial.println(Ethernet.localIP());
  378. }
  379. /* We'll assume the Ethernet connection is ready to go. */
  380. #endif
  381. Serial.println(F("********************************************************"));
  382. Serial.print(F(" wolfSSL Example Server IP = "));
  383. #if defined(USING_WIFI)
  384. Serial.println(WiFi.localIP());
  385. #else
  386. Serial.println(Ethernet.localIP());
  387. #endif
  388. /* In server mode, there's no host definition. */
  389. /* See companion example: wolfssl_client.ino */
  390. Serial.println(F("********************************************************"));
  391. Serial.println(F("Setup network complete."));
  392. return ret;
  393. }
  394. /*****************************************************************************/
  395. /* Arduino setup_wolfssl() */
  396. /*****************************************************************************/
  397. int setup_wolfssl(void) {
  398. int ret = 0;
  399. WOLFSSL_METHOD* method;
  400. /* Show a revision of wolfssl user_settings.h file in use when available: */
  401. #if defined(WOLFSSL_USER_SETTINGS_ID)
  402. Serial.print(F("WOLFSSL_USER_SETTINGS_ID: "));
  403. Serial.println(F(WOLFSSL_USER_SETTINGS_ID));
  404. #else
  405. Serial.println(F("No WOLFSSL_USER_SETTINGS_ID found."));
  406. #endif
  407. #if defined(NO_WOLFSSL_SERVER)
  408. Serial.println(F("wolfSSL server code disabled to save space."));
  409. #endif
  410. #if defined(NO_WOLFSSL_CLIENT)
  411. Serial.println(F("wolfSSL client code disabled to save space."));
  412. #endif
  413. #if defined(DEBUG_WOLFSSL)
  414. wolfSSL_Debugging_ON();
  415. Serial.println(F("wolfSSL Debugging is On!"));
  416. #else
  417. Serial.println(F("wolfSSL Debugging is Off! (enable with DEBUG_WOLFSSL)"));
  418. #endif
  419. /* See ssl.c for TLS cache settings. Larger cache = use more RAM. */
  420. #if defined(NO_SESSION_CACHE)
  421. Serial.println(F("wolfSSL TLS NO_SESSION_CACHE"));
  422. #elif defined(MICRO_SESSION_CACHEx)
  423. Serial.println(F("wolfSSL TLS MICRO_SESSION_CACHE"));
  424. #elif defined(SMALL_SESSION_CACHE)
  425. Serial.println(F("wolfSSL TLS SMALL_SESSION_CACHE"));
  426. #elif defined(MEDIUM_SESSION_CACHE)
  427. Serial.println(F("wolfSSL TLS MEDIUM_SESSION_CACHE"));
  428. #elif defined(BIG_SESSION_CACHE)
  429. Serial.println(F("wolfSSL TLS BIG_SESSION_CACHE"));
  430. #elif defined(HUGE_SESSION_CACHE)
  431. Serial.println(F("wolfSSL TLS HUGE_SESSION_CACHE"));
  432. #elif defined(HUGE_SESSION_CACHE)
  433. Serial.println(F("wolfSSL TLS HUGE_SESSION_CACHE"));
  434. #else
  435. Serial.println(F("WARNING: Unknown or no TLS session cache setting."));
  436. /* See wolfssl/src/ssl.c for amount of memory used.
  437. * It is best on embedded devices to choose a TLS session cache size. */
  438. #endif
  439. ret = wolfSSL_Init();
  440. if (ret == WOLFSSL_SUCCESS) {
  441. Serial.println("Successfully called wolfSSL_Init");
  442. }
  443. else {
  444. Serial.println("ERROR: wolfSSL_Init failed");
  445. }
  446. /* See companion server example with wolfSSLv23_server_method here.
  447. * method = wolfSSLv23_client_method()); SSL 3.0 - TLS 1.3.
  448. * method = wolfTLSv1_2_client_method(); only TLS 1.2
  449. * method = wolfTLSv1_3_client_method(); only TLS 1.3
  450. *
  451. * see Arduino\libraries\wolfssl\src\user_settings.h */
  452. Serial.println("Here we go!");
  453. method = wolfSSLv23_server_method();
  454. if (method == NULL) {
  455. Serial.println(F("unable to get wolfssl server method"));
  456. fail_wait();
  457. }
  458. ctx = wolfSSL_CTX_new(method);
  459. if (ctx == NULL) {
  460. Serial.println(F("unable to get ctx"));
  461. fail_wait();
  462. }
  463. return ret;
  464. }
  465. /*****************************************************************************/
  466. /* Arduino setup_certificates() */
  467. /*****************************************************************************/
  468. int setup_certificates(void) {
  469. int ret = 0;
  470. Serial.println(F("Initializing certificates..."));
  471. show_memory();
  472. /* Use built-in validation, No verification callback function: */
  473. wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
  474. /* Certificate */
  475. Serial.println("Initializing certificates...");
  476. ret = wolfSSL_CTX_use_certificate_buffer(ctx,
  477. CTX_SERVER_CERT,
  478. CTX_SERVER_CERT_SIZE,
  479. CTX_CA_CERT_TYPE);
  480. if (ret == WOLFSSL_SUCCESS) {
  481. Serial.print("Success: use certificate: ");
  482. Serial.println(xstr(CTX_SERVER_CERT));
  483. }
  484. else {
  485. Serial.print("Error: wolfSSL_CTX_use_certificate_buffer failed: ");
  486. wc_ErrorString(ret, wc_error_message);
  487. Serial.println(wc_error_message);
  488. fail_wait();
  489. }
  490. /* Setup private server key */
  491. ret = wolfSSL_CTX_use_PrivateKey_buffer(ctx,
  492. CTX_SERVER_KEY,
  493. CTX_SERVER_KEY_SIZE,
  494. CTX_SERVER_KEY_TYPE);
  495. if (ret == WOLFSSL_SUCCESS) {
  496. Serial.print("Success: use private key buffer: ");
  497. Serial.println(xstr(CTX_SERVER_KEY));
  498. }
  499. else {
  500. Serial.print("Error: wolfSSL_CTX_use_PrivateKey_buffer failed: ");
  501. wc_ErrorString(ret, wc_error_message);
  502. Serial.println(wc_error_message);
  503. fail_wait();
  504. }
  505. return ret;
  506. } /* Arduino setup */
  507. /*****************************************************************************/
  508. /*****************************************************************************/
  509. /* Arduino setup() */
  510. /*****************************************************************************/
  511. /*****************************************************************************/
  512. void setup(void) {
  513. int i = 0;
  514. Serial.begin(SERIAL_BAUD);
  515. while (!Serial && (i < 10)) {
  516. /* wait for serial port to connect. Needed for native USB port only */
  517. delay(1000);
  518. i++;
  519. }
  520. Serial.println(F(""));
  521. Serial.println(F(""));
  522. Serial.println(F("wolfSSL TLS Server Example Startup."));
  523. /* define DEBUG_WOLFSSL in wolfSSL user_settings.h for diagnostics */
  524. #if defined(DEBUG_WOLFSSL)
  525. wolfSSL_Debugging_ON();
  526. #endif
  527. /* Optionally pre-allocate a large block of memory for testing */
  528. #if defined(MEMORY_STRESS_TEST)
  529. Serial.println(F("WARNING: Memory Stress Test Active!"));
  530. Serial.print(F("Allocating extra memory: "));
  531. Serial.print(MEMORY_STRESS_INITIAL);
  532. Serial.println(F(" bytes..."));
  533. memory_stress[mem_ctr] = (char*)malloc(MEMORY_STRESS_INITIAL);
  534. show_memory();
  535. #endif
  536. setup_hardware();
  537. setup_network();
  538. setup_datetime();
  539. setup_wolfssl();
  540. setup_certificates();
  541. /* Initialize wolfSSL using callback functions. */
  542. wolfSSL_SetIOSend(ctx, EthernetSend);
  543. wolfSSL_SetIORecv(ctx, EthernetReceive);
  544. #if defined THIS_USER_SETTINGS_VERSION
  545. Serial.print(F("This user_settings.h version:"))
  546. Serial.println(THIS_USER_SETTINGS_VERSION)
  547. #endif
  548. /* Start the server
  549. * See https://www.arduino.cc/reference/en/libraries/ethernet/server.begin/
  550. */
  551. Serial.println(F("Completed Arduino setup()"));
  552. server.begin();
  553. Serial.println("Begin Server... (waiting for remote client to connect)");
  554. /* See companion wolfssl_client.ino code */
  555. return;
  556. } /* Arduino setup */
  557. /*****************************************************************************/
  558. /* wolfSSL error_check() */
  559. /*****************************************************************************/
  560. int error_check(int this_ret, bool halt_on_error,
  561. const __FlashStringHelper* message) {
  562. int ret = 0;
  563. if (this_ret == WOLFSSL_SUCCESS) {
  564. Serial.print(F("Success: "));
  565. Serial.println(message);
  566. }
  567. else {
  568. Serial.print(F("ERROR: return = "));
  569. Serial.print(this_ret);
  570. Serial.print(F(": "));
  571. Serial.println(message);
  572. Serial.println(wc_GetErrorString(this_ret));
  573. if (halt_on_error) {
  574. fail_wait();
  575. }
  576. }
  577. show_memory();
  578. return ret;
  579. } /* error_check */
  580. /*****************************************************************************/
  581. /* wolfSSL error_check_ssl */
  582. /* Parameters: */
  583. /* ssl is the current WOLFSSL object pointer */
  584. /* halt_on_error set to true to suspend operations for critical error */
  585. /* message is expected to be a memory-efficient F("") macro string */
  586. /*****************************************************************************/
  587. int error_check_ssl(WOLFSSL* ssl, int this_ret, bool halt_on_error,
  588. const __FlashStringHelper* message) {
  589. int err = 0;
  590. if (ssl == NULL) {
  591. Serial.println(F("ssl is Null; Unable to allocate SSL object?"));
  592. #ifndef DEBUG_WOLFSSL
  593. Serial.println(F("Define DEBUG_WOLFSSL in user_settings.h for more."));
  594. #else
  595. Serial.println(F("See wolfssl/wolfcrypt/error-crypt.h for codes."));
  596. #endif
  597. Serial.print(F("ERROR: "));
  598. Serial.println(message);
  599. show_memory();
  600. if (halt_on_error) {
  601. fail_wait();
  602. }
  603. }
  604. else {
  605. err = wolfSSL_get_error(ssl, this_ret);
  606. if (err == WOLFSSL_SUCCESS) {
  607. Serial.print(F("Success m: "));
  608. Serial.println(message);
  609. }
  610. else {
  611. if (err < 0) {
  612. wolfSSL_ERR_error_string(err, errBuf);
  613. Serial.print(F("WOLFSSL Error: "));
  614. Serial.print(err);
  615. Serial.print(F("; "));
  616. Serial.println(errBuf);
  617. }
  618. else {
  619. Serial.println(F("Success: ssl object."));
  620. }
  621. }
  622. }
  623. return err;
  624. }
  625. /*****************************************************************************/
  626. /*****************************************************************************/
  627. /* Arduino loop() */
  628. /*****************************************************************************/
  629. /*****************************************************************************/
  630. void loop() {
  631. char errBuf[80] = "(no error";
  632. char reply[80] = "(no reply)";
  633. const char msg[] = "I hear you fa shizzle!";
  634. const char* cipherName;
  635. int input = 0;
  636. int replySz = 0;
  637. int retry_shutdown = SHUTDOWN_DELAY_MS; /* max try, once per millisecond */
  638. int ret = 0;
  639. IPAddress broadcast_address(255, 255, 255, 255);
  640. /* Listen for incoming client requests. */
  641. client = server.available();
  642. if (client) {
  643. Serial.println("Have Client");
  644. while (!client.connected()) {
  645. /* wait for the client to actually connect */
  646. delay(10);
  647. }
  648. Serial.print("Client connected from remote IP: ");
  649. Serial.println(client.remoteIP());
  650. ssl = wolfSSL_new(ctx);
  651. if (ssl == NULL) {
  652. Serial.println("Unable to allocate SSL object");
  653. fail_wait();
  654. }
  655. ret = wolfSSL_accept(ssl);
  656. if (ret != WOLFSSL_SUCCESS) {
  657. ret = wolfSSL_get_error(ssl, 0);
  658. wolfSSL_ERR_error_string(ret, errBuf);
  659. Serial.print("TLS Accept Error: ");
  660. Serial.println(errBuf);
  661. }
  662. cipherName = wolfSSL_get_cipher(ssl);
  663. Serial.print("SSL cipher suite is ");
  664. Serial.println(cipherName);
  665. Serial.print("Server Read: ");
  666. while (!client.available()) {
  667. /* wait for data */
  668. }
  669. /* read data */
  670. while (wolfSSL_pending(ssl)) {
  671. input = wolfSSL_read(ssl, reply, sizeof(reply) - 1);
  672. if (input < 0) {
  673. ret = wolfSSL_get_error(ssl, 0);
  674. wolfSSL_ERR_error_string(ret, errBuf);
  675. Serial.print("TLS Read Error: ");
  676. Serial.println(errBuf);
  677. break;
  678. }
  679. else if (input > 0) {
  680. replySz = input;
  681. reply[input] = '\0';
  682. Serial.print(reply);
  683. }
  684. else {
  685. Serial.println("<end of reply, input == 0>");
  686. }
  687. }
  688. /* Write our message into reply buffer to send */
  689. memset(reply, 0, sizeof(reply));
  690. memcpy(reply, msg, sizeof(msg));
  691. replySz = strnlen(reply, sizeof(reply));
  692. Serial.println("Sending reply...");
  693. if ((wolfSSL_write(ssl, reply, replySz)) != replySz) {
  694. ret = wolfSSL_get_error(ssl, 0);
  695. wolfSSL_ERR_error_string(ret, errBuf);
  696. Serial.print("TLS Write Error: ");
  697. Serial.println(errBuf);
  698. }
  699. else {
  700. Serial.println("Reply sent!");
  701. }
  702. Serial.println("Shutdown!");
  703. do {
  704. delay(1);
  705. retry_shutdown--;
  706. ret = wolfSSL_shutdown(ssl);
  707. } while ((ret == WOLFSSL_SHUTDOWN_NOT_DONE) && (retry_shutdown > 0));
  708. if (retry_shutdown <= 0) {
  709. /* if wolfSSL_free is called before properly shutting down the
  710. * ssl object, undesired results may occur. */
  711. Serial.println("Warning! Shutdown did not properly complete.");
  712. }
  713. wolfSSL_free(ssl);
  714. Serial.println("Connection complete.");
  715. if (REPEAT_CONNECTION) {
  716. Serial.println();
  717. Serial.println("Waiting for next connection.");
  718. }
  719. else {
  720. client.stop();
  721. Serial.println("Done!");
  722. while (1) {
  723. /* wait forever if not repeating */
  724. delay(100);
  725. }
  726. }
  727. }
  728. else {
  729. /* Serial.println("Client not connected. Trying again..."); */
  730. }
  731. delay(100);
  732. } /* Arduino loop repeats */