wolfssl_example.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  1. /* wolfssl_example.c
  2. *
  3. * Copyright (C) 2006-2022 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. #include "wolfssl_example.h"
  22. /* force certificate test buffers to be included via headers */
  23. #undef USE_CERT_BUFFERS_2048
  24. #define USE_CERT_BUFFERS_2048
  25. #undef USE_CERT_BUFFERS_256
  26. #define USE_CERT_BUFFERS_256
  27. #include <wolfssl/certs_test.h>
  28. #include <wolfssl/wolfcrypt/hash.h> /* WC_MAX_DIGEST_SIZE */
  29. #ifndef SINGLE_THREADED
  30. #include <cmsis_os.h>
  31. #ifdef WOLFSSL_DEBUG_MEMORY
  32. /* for memory debugging */
  33. #include <task.h>
  34. #endif
  35. #endif
  36. #include <stdio.h>
  37. #include <string.h>
  38. /*****************************************************************************
  39. * Configuration
  40. ****************************************************************************/
  41. /* Defaults for configuration parameters */
  42. #define BENCH_DEFAULT_HOST "localhost"
  43. #define BENCH_DEFAULT_PORT 11112
  44. #define BENCH_RUNTIME_SEC 20
  45. #define BENCH_SHOW_PEER_INFO 1
  46. #define TEST_PACKET_SIZE (2 * 1024) /* TLS packet size */
  47. #ifdef BENCH_EMBEDDED
  48. #define TEST_MAX_SIZE (4 * 1024)
  49. #else
  50. #define TEST_MAX_SIZE (32 * 1024) /* Total bytes to benchmark */
  51. #endif
  52. /* Must be large enough to handle max packet size - TLS header MAX_MSG_EXTRA + MAX DIGEST */
  53. #define MEM_BUFFER_SZ (TEST_PACKET_SIZE + 38 + WC_MAX_DIGEST_SIZE)
  54. /* make sure memory buffer size is large enough */
  55. #if MEM_BUFFER_SZ < 2048
  56. #undef MEM_BUFFER_SZ
  57. #define MEM_BUFFER_SZ 2048
  58. #endif
  59. #define SHOW_VERBOSE 0 /* 0=tab del (minimal), 1=info, 2=debug, 3=debug w/wolf logs */
  60. #ifndef WOLFSSL_CIPHER_LIST_MAX_SIZE
  61. #define WOLFSSL_CIPHER_LIST_MAX_SIZE 2048
  62. #endif
  63. #if 0
  64. /* define this to test only a specific cipher suite(s) (colon separated) */
  65. #define TEST_CIPHER_SUITE "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256"
  66. #endif
  67. #if 0
  68. /* use non-blocking mode for read/write IO */
  69. #define BENCH_USE_NONBLOCK
  70. #endif
  71. #ifndef RECV_WAIT_TIMEOUT
  72. #define RECV_WAIT_TIMEOUT 10000
  73. #endif
  74. /*****************************************************************************
  75. * Private types/enumerations/variables
  76. ****************************************************************************/
  77. #ifdef WOLFSSL_STATIC_MEMORY
  78. #if 1 /* on-chip RAM */
  79. #define RAM_STATIC
  80. #else /* external RAM */
  81. /* requires .ld to be updated with ".extram" section */
  82. #define RAM_STATIC __attribute__ ((section (".extram")))
  83. #endif
  84. #define WOLF_GEN_MEM (20*1024)
  85. #define WOLF_TLS_GEN_MEM (90*1024)
  86. #define WOLF_TLS_IO_POOL_MEM (35*1024)
  87. RAM_STATIC static byte gWolfMem[WOLF_GEN_MEM];
  88. RAM_STATIC static byte gWolfCTXCli[WOLF_TLS_GEN_MEM];
  89. RAM_STATIC static byte gWolfIOCli[WOLF_TLS_IO_POOL_MEM];
  90. RAM_STATIC static byte gWolfCTXSrv[WOLF_TLS_GEN_MEM];
  91. RAM_STATIC static byte gWolfIOSrv[WOLF_TLS_IO_POOL_MEM];
  92. WOLFSSL_HEAP_HINT* HEAP_HINT = NULL;
  93. #endif /* WOLFSSL_STATIC_MEMORY */
  94. /* This sets which UART to use for the console. It is something you will have
  95. * to configure in STMCubeIDE and then change here. */
  96. #ifndef HAL_CONSOLE_UART
  97. #define HAL_CONSOLE_UART huart4
  98. #endif
  99. extern UART_HandleTypeDef HAL_CONSOLE_UART;
  100. /*****************************************************************************
  101. * Public types/enumerations/variables
  102. ****************************************************************************/
  103. typedef struct func_args {
  104. int argc;
  105. char** argv;
  106. int return_code;
  107. } func_args;
  108. const char menu1[] = "\n"
  109. "\tt. wolfCrypt Test\n"
  110. "\tb. wolfCrypt Benchmark\n"
  111. "\tl. wolfSSL TLS Bench\n"
  112. "\te. Show Cipher List\n"
  113. "\ts. Run TLS 1.3 Server over UART\n"
  114. "\tc. Run TLS 1.3 Client over UART\n";
  115. static void PrintMemStats(void);
  116. double current_time(void);
  117. #if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) && \
  118. !defined(WOLFCRYPT_ONLY) && !defined(SINGLE_THREADED)
  119. static const char* kShutdown = "shutdown";
  120. static const char* kTestStr =
  121. "Biodiesel cupidatat marfa, cliche aute put a bird on it incididunt elit\n"
  122. "polaroid. Sunt tattooed bespoke reprehenderit. Sint twee organic id\n"
  123. "marfa. Commodo veniam ad esse gastropub. 3 wolf moon sartorial vero,\n"
  124. "plaid delectus biodiesel squid +1 vice. Post-ironic keffiyeh leggings\n"
  125. "selfies cray fap hoodie, forage anim. Carles cupidatat shoreditch, VHS\n"
  126. "small batch meggings kogi dolore food truck bespoke gastropub.\n"
  127. "\n"
  128. "Terry richardson adipisicing actually typewriter tumblr, twee whatever\n"
  129. "four loko you probably haven't heard of them high life. Messenger bag\n"
  130. "whatever tattooed deep v mlkshk. Brooklyn pinterest assumenda chillwave\n"
  131. "et, banksy ullamco messenger bag umami pariatur direct trade forage.\n"
  132. "Typewriter culpa try-hard, pariatur sint brooklyn meggings. Gentrify\n"
  133. "food truck next level, tousled irony non semiotics PBR ethical anim cred\n"
  134. "readymade. Mumblecore brunch lomo odd future, portland organic terry\n"
  135. "richardson elit leggings adipisicing ennui raw denim banjo hella. Godard\n"
  136. "mixtape polaroid, pork belly readymade organic cray typewriter helvetica\n"
  137. "four loko whatever street art yr farm-to-table.\n"
  138. "\n"
  139. "Vinyl keytar vice tofu. Locavore you probably haven't heard of them pug\n"
  140. "pickled, hella tonx labore truffaut DIY mlkshk elit cosby sweater sint\n"
  141. "et mumblecore. Elit swag semiotics, reprehenderit DIY sartorial nisi ugh\n"
  142. "nesciunt pug pork belly wayfarers selfies delectus. Ethical hoodie\n"
  143. "seitan fingerstache kale chips. Terry richardson artisan williamsburg,\n"
  144. "eiusmod fanny pack irony tonx ennui lo-fi incididunt tofu YOLO\n"
  145. "readymade. 8-bit sed ethnic beard officia. Pour-over iphone DIY butcher,\n"
  146. "ethnic art party qui letterpress nisi proident jean shorts mlkshk\n"
  147. "locavore.\n"
  148. "\n"
  149. "Narwhal flexitarian letterpress, do gluten-free voluptate next level\n"
  150. "banh mi tonx incididunt carles DIY. Odd future nulla 8-bit beard ut\n"
  151. "cillum pickled velit, YOLO officia you probably haven't heard of them\n"
  152. "trust fund gastropub. Nisi adipisicing tattooed, Austin mlkshk 90's\n"
  153. "small batch american apparel. Put a bird on it cosby sweater before they\n"
  154. "sold out pork belly kogi hella. Street art mollit sustainable polaroid,\n"
  155. "DIY ethnic ea pug beard dreamcatcher cosby sweater magna scenester nisi.\n"
  156. "Sed pork belly skateboard mollit, labore proident eiusmod. Sriracha\n"
  157. "excepteur cosby sweater, anim deserunt laborum eu aliquip ethical et\n"
  158. "neutra PBR selvage.\n"
  159. "\n"
  160. "Raw denim pork belly truffaut, irony plaid sustainable put a bird on it\n"
  161. "next level jean shorts exercitation. Hashtag keytar whatever, nihil\n"
  162. "authentic aliquip disrupt laborum. Tattooed selfies deserunt trust fund\n"
  163. "wayfarers. 3 wolf moon synth church-key sartorial, gastropub leggings\n"
  164. "tattooed. Labore high life commodo, meggings raw denim fingerstache pug\n"
  165. "trust fund leggings seitan forage. Nostrud ullamco duis, reprehenderit\n"
  166. "incididunt flannel sustainable helvetica pork belly pug banksy you\n"
  167. "probably haven't heard of them nesciunt farm-to-table. Disrupt nostrud\n"
  168. "mollit magna, sriracha sartorial helvetica.\n"
  169. "\n"
  170. "Nulla kogi reprehenderit, skateboard sustainable duis adipisicing viral\n"
  171. "ad fanny pack salvia. Fanny pack trust fund you probably haven't heard\n"
  172. "of them YOLO vice nihil. Keffiyeh cray lo-fi pinterest cardigan aliqua,\n"
  173. "reprehenderit aute. Culpa tousled williamsburg, marfa lomo actually anim\n"
  174. "skateboard. Iphone aliqua ugh, semiotics pariatur vero readymade\n"
  175. "organic. Marfa squid nulla, in laborum disrupt laboris irure gastropub.\n"
  176. "Veniam sunt food truck leggings, sint vinyl fap.\n"
  177. "\n"
  178. "Hella dolore pork belly, truffaut carles you probably haven't heard of\n"
  179. "them PBR helvetica in sapiente. Fashion axe ugh bushwick american\n"
  180. "apparel. Fingerstache sed iphone, jean shorts blue bottle nisi bushwick\n"
  181. "flexitarian officia veniam plaid bespoke fap YOLO lo-fi. Blog\n"
  182. "letterpress mumblecore, food truck id cray brooklyn cillum ad sed.\n"
  183. "Assumenda chambray wayfarers vinyl mixtape sustainable. VHS vinyl\n"
  184. "delectus, culpa williamsburg polaroid cliche swag church-key synth kogi\n"
  185. "magna pop-up literally. Swag thundercats ennui shoreditch vegan\n"
  186. "pitchfork neutra truffaut etsy, sed single-origin coffee craft beer.\n"
  187. "\n"
  188. "Odio letterpress brooklyn elit. Nulla single-origin coffee in occaecat\n"
  189. "meggings. Irony meggings 8-bit, chillwave lo-fi adipisicing cred\n"
  190. "dreamcatcher veniam. Put a bird on it irony umami, trust fund bushwick\n"
  191. "locavore kale chips. Sriracha swag thundercats, chillwave disrupt\n"
  192. "tousled beard mollit mustache leggings portland next level. Nihil esse\n"
  193. "est, skateboard art party etsy thundercats sed dreamcatcher ut iphone\n"
  194. "swag consectetur et. Irure skateboard banjo, nulla deserunt messenger\n"
  195. "bag dolor terry richardson sapiente.\n";
  196. #if !defined(NO_DH)
  197. #define MIN_DHKEY_BITS 1024
  198. /* dh2048 p */
  199. static const unsigned char p[] =
  200. {
  201. 0xb0, 0xa1, 0x08, 0x06, 0x9c, 0x08, 0x13, 0xba, 0x59, 0x06, 0x3c, 0xbc, 0x30,
  202. 0xd5, 0xf5, 0x00, 0xc1, 0x4f, 0x44, 0xa7, 0xd6, 0xef, 0x4a, 0xc6, 0x25, 0x27,
  203. 0x1c, 0xe8, 0xd2, 0x96, 0x53, 0x0a, 0x5c, 0x91, 0xdd, 0xa2, 0xc2, 0x94, 0x84,
  204. 0xbf, 0x7d, 0xb2, 0x44, 0x9f, 0x9b, 0xd2, 0xc1, 0x8a, 0xc5, 0xbe, 0x72, 0x5c,
  205. 0xa7, 0xe7, 0x91, 0xe6, 0xd4, 0x9f, 0x73, 0x07, 0x85, 0x5b, 0x66, 0x48, 0xc7,
  206. 0x70, 0xfa, 0xb4, 0xee, 0x02, 0xc9, 0x3d, 0x9a, 0x4a, 0xda, 0x3d, 0xc1, 0x46,
  207. 0x3e, 0x19, 0x69, 0xd1, 0x17, 0x46, 0x07, 0xa3, 0x4d, 0x9f, 0x2b, 0x96, 0x17,
  208. 0x39, 0x6d, 0x30, 0x8d, 0x2a, 0xf3, 0x94, 0xd3, 0x75, 0xcf, 0xa0, 0x75, 0xe6,
  209. 0xf2, 0x92, 0x1f, 0x1a, 0x70, 0x05, 0xaa, 0x04, 0x83, 0x57, 0x30, 0xfb, 0xda,
  210. 0x76, 0x93, 0x38, 0x50, 0xe8, 0x27, 0xfd, 0x63, 0xee, 0x3c, 0xe5, 0xb7, 0xc8,
  211. 0x09, 0xae, 0x6f, 0x50, 0x35, 0x8e, 0x84, 0xce, 0x4a, 0x00, 0xe9, 0x12, 0x7e,
  212. 0x5a, 0x31, 0xd7, 0x33, 0xfc, 0x21, 0x13, 0x76, 0xcc, 0x16, 0x30, 0xdb, 0x0c,
  213. 0xfc, 0xc5, 0x62, 0xa7, 0x35, 0xb8, 0xef, 0xb7, 0xb0, 0xac, 0xc0, 0x36, 0xf6,
  214. 0xd9, 0xc9, 0x46, 0x48, 0xf9, 0x40, 0x90, 0x00, 0x2b, 0x1b, 0xaa, 0x6c, 0xe3,
  215. 0x1a, 0xc3, 0x0b, 0x03, 0x9e, 0x1b, 0xc2, 0x46, 0xe4, 0x48, 0x4e, 0x22, 0x73,
  216. 0x6f, 0xc3, 0x5f, 0xd4, 0x9a, 0xd6, 0x30, 0x07, 0x48, 0xd6, 0x8c, 0x90, 0xab,
  217. 0xd4, 0xf6, 0xf1, 0xe3, 0x48, 0xd3, 0x58, 0x4b, 0xa6, 0xb9, 0xcd, 0x29, 0xbf,
  218. 0x68, 0x1f, 0x08, 0x4b, 0x63, 0x86, 0x2f, 0x5c, 0x6b, 0xd6, 0xb6, 0x06, 0x65,
  219. 0xf7, 0xa6, 0xdc, 0x00, 0x67, 0x6b, 0xbb, 0xc3, 0xa9, 0x41, 0x83, 0xfb, 0xc7,
  220. 0xfa, 0xc8, 0xe2, 0x1e, 0x7e, 0xaf, 0x00, 0x3f, 0x93
  221. };
  222. /* dh2048 g */
  223. static const unsigned char g[] =
  224. {
  225. 0x02,
  226. };
  227. #endif /* !NO_DH */
  228. typedef struct {
  229. unsigned char buf[MEM_BUFFER_SZ];
  230. int write_bytes;
  231. int write_idx;
  232. int read_bytes;
  233. int read_idx;
  234. } memBuf_t;
  235. typedef struct {
  236. double connTime;
  237. double rxTime;
  238. double txTime;
  239. int connCount;
  240. int rxTotal;
  241. int txTotal;
  242. } stats_t;
  243. typedef struct {
  244. int ret;
  245. osThreadId threadId;
  246. #ifdef CMSIS_OS2_H_
  247. osSemaphoreId_t mutex;
  248. #else
  249. osThreadDef_t threadDef;
  250. osSemaphoreDef_t mutexDef;
  251. osSemaphoreId mutex;
  252. #endif
  253. byte shutdown:1;
  254. byte done:1;
  255. } side_t;
  256. typedef struct {
  257. const char* cipher;
  258. const char* host;
  259. word32 port;
  260. int packetSize; /* The data payload size in the packet */
  261. int maxSize;
  262. int runTimeSec;
  263. int showPeerInfo;
  264. int showVerbose;
  265. int doShutdown;
  266. side_t client;
  267. side_t server;
  268. /* client messages to server in memory */
  269. memBuf_t to_server;
  270. /* server messages to client in memory */
  271. memBuf_t to_client;
  272. /* server */
  273. stats_t server_stats;
  274. /* client */
  275. stats_t client_stats;
  276. } info_t;
  277. /*****************************************************************************
  278. * Private functions
  279. ****************************************************************************/
  280. static double gettime_secs(int reset)
  281. {
  282. return current_time();
  283. }
  284. static void PrintTlsStats(stats_t* wcStat, const char* desc, const char* cipher, int verbose)
  285. {
  286. const char* formatStr;
  287. if (verbose) {
  288. formatStr = "wolfSSL %s Benchmark on %s:\n"
  289. "\tTotal : %9d bytes\n"
  290. "\tNum Conns : %9d\n"
  291. "\tRx Total : %9.3f ms\n"
  292. "\tTx Total : %9.3f ms\n"
  293. "\tRx : %9.3f MB/s\n"
  294. "\tTx : %9.3f MB/s\n"
  295. "\tConnect : %9.3f ms\n"
  296. "\tConnect Avg : %9.3f ms\n";
  297. }
  298. else {
  299. formatStr = "%-6s %-33s %11d %9d %9.3f %9.3f %9.3f %9.3f %17.3f %15.3f\n";
  300. }
  301. printf(formatStr,
  302. desc,
  303. cipher,
  304. wcStat->txTotal + wcStat->rxTotal,
  305. wcStat->connCount,
  306. wcStat->rxTime * 1000,
  307. wcStat->txTime * 1000,
  308. wcStat->rxTotal / wcStat->rxTime / 1024 / 1024,
  309. wcStat->txTotal / wcStat->txTime / 1024 / 1024,
  310. wcStat->connTime * 1000,
  311. wcStat->connTime * 1000 / wcStat->connCount);
  312. }
  313. #if defined(KEEP_PEER_CERT) || defined(KEEP_OUR_CERT)
  314. static const char* client_showx509_msg[] = {
  315. "issuer",
  316. "subject",
  317. "altname",
  318. "serial number",
  319. NULL
  320. };
  321. static void ShowX509(WOLFSSL_X509* x509, const char* hdr)
  322. {
  323. char* altName;
  324. char* issuer;
  325. char* subject;
  326. byte serial[32];
  327. int ret;
  328. int sz = sizeof(serial);
  329. const char** words = client_showx509_msg;
  330. if (x509 == NULL) {
  331. printf("%s No Cert\n", hdr);
  332. return;
  333. }
  334. issuer = wolfSSL_X509_NAME_oneline(
  335. wolfSSL_X509_get_issuer_name(x509), 0, 0);
  336. subject = wolfSSL_X509_NAME_oneline(
  337. wolfSSL_X509_get_subject_name(x509), 0, 0);
  338. printf("%s\n %s : %s\n %s: %s\n", hdr, words[0], issuer, words[1], subject);
  339. while ( (altName = wolfSSL_X509_get_next_altname(x509)) != NULL)
  340. printf(" %s = %s\n", words[2], altName);
  341. ret = wolfSSL_X509_get_serial_number(x509, serial, &sz);
  342. if (ret == WOLFSSL_SUCCESS) {
  343. int i;
  344. int strLen;
  345. char serialMsg[80];
  346. /* testsuite has multiple threads writing to stdout, get output
  347. message ready to write once */
  348. strLen = sprintf(serialMsg, " %s", words[3]);
  349. for (i = 0; i < sz; i++)
  350. sprintf(serialMsg + strLen + (i*3), ":%02x ", serial[i]);
  351. printf("%s\n", serialMsg);
  352. }
  353. XFREE(subject, 0, DYNAMIC_TYPE_OPENSSL);
  354. XFREE(issuer, 0, DYNAMIC_TYPE_OPENSSL);
  355. #if defined(OPENSSL_EXTRA)
  356. {
  357. WOLFSSL_BIO* bio;
  358. char buf[256]; /* should be size of ASN_NAME_MAX */
  359. int textSz;
  360. /* print out domain component if certificate has it */
  361. textSz = wolfSSL_X509_NAME_get_text_by_NID(
  362. wolfSSL_X509_get_subject_name(x509), NID_domainComponent,
  363. buf, sizeof(buf));
  364. if (textSz > 0) {
  365. printf("Domain Component = %s\n", buf);
  366. }
  367. bio = wolfSSL_BIO_new(wolfSSL_BIO_s_file());
  368. if (bio != NULL) {
  369. wolfSSL_BIO_set_fp(bio, stdout, BIO_NOCLOSE);
  370. wolfSSL_X509_print(bio, x509);
  371. wolfSSL_BIO_free(bio);
  372. }
  373. }
  374. #endif /* OPENSSL_EXTRA */
  375. }
  376. #endif
  377. static const char* client_showpeer_msg[] = {
  378. "SSL version is",
  379. "SSL cipher suite is",
  380. "SSL curve name is",
  381. "SSL DH size is",
  382. "SSL reused session",
  383. "Alternate cert chain used",
  384. "peer's cert info:",
  385. NULL
  386. };
  387. static void ShowPeer(WOLFSSL* ssl)
  388. {
  389. WOLFSSL_CIPHER* cipher;
  390. const char** words = client_showpeer_msg;
  391. #if defined(HAVE_ECC) || !defined(NO_DH)
  392. const char *name;
  393. #endif
  394. #ifndef NO_DH
  395. int bits;
  396. #endif
  397. #ifdef KEEP_PEER_CERT
  398. WOLFSSL_X509* peer = wolfSSL_get_peer_certificate(ssl);
  399. if (peer)
  400. ShowX509(peer, words[6]);
  401. else
  402. printf("peer has no cert!\n");
  403. wolfSSL_FreeX509(peer);
  404. #endif
  405. #if defined(KEEP_OUR_CERT) && \
  406. (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL))
  407. ShowX509(wolfSSL_get_certificate(ssl), "our cert info:");
  408. printf("Peer verify result = %lu\n", wolfSSL_get_verify_result(ssl));
  409. #endif /* SHOW_CERTS && KEEP_OUR_CERT */
  410. printf("%s %s\n", words[0], wolfSSL_get_version(ssl));
  411. cipher = wolfSSL_get_current_cipher(ssl);
  412. printf("%s %s\n", words[1], wolfSSL_CIPHER_get_name(cipher));
  413. #if defined(HAVE_ECC) || !defined(NO_DH)
  414. if ((name = wolfSSL_get_curve_name(ssl)) != NULL)
  415. printf("%s %s\n", words[2], name);
  416. #endif
  417. #ifndef NO_DH
  418. else if ((bits = wolfSSL_GetDhKey_Sz(ssl)) > 0)
  419. printf("%s %d bits\n", words[3], bits);
  420. #endif
  421. if (wolfSSL_session_reused(ssl))
  422. printf("%s\n", words[4]);
  423. #ifdef WOLFSSL_ALT_CERT_CHAINS
  424. if (wolfSSL_is_peer_alt_cert_chain(ssl))
  425. printf("%s\n", words[5]);
  426. #endif
  427. (void)ssl;
  428. }
  429. /* server send callback */
  430. static int ServerMemSend(info_t* info, char* buf, int sz)
  431. {
  432. #ifdef CMSIS_OS2_H_
  433. osSemaphoreAcquire(info->client.mutex, osWaitForever);
  434. #else
  435. osSemaphoreWait(info->client.mutex, osWaitForever);
  436. #endif
  437. #ifndef BENCH_USE_NONBLOCK
  438. /* check for overflow */
  439. if (info->to_client.write_idx + sz > MEM_BUFFER_SZ) {
  440. osSemaphoreRelease(info->client.mutex);
  441. printf("ServerMemSend overflow\n");
  442. return -1;
  443. }
  444. #else
  445. if (info->to_client.write_idx + sz > MEM_BUFFER_SZ)
  446. sz = MEM_BUFFER_SZ - info->to_client.write_idx;
  447. #endif
  448. if (info->showVerbose >= 2)
  449. printf("Server Send: %d\n", sz);
  450. XMEMCPY(&info->to_client.buf[info->to_client.write_idx], buf, sz);
  451. info->to_client.write_idx += sz;
  452. info->to_client.write_bytes += sz;
  453. #ifdef CMSIS_OS2_H_
  454. osThreadFlagsSet(info->client.threadId, 1);
  455. #else
  456. osSignalSet(info->client.threadId, 1);
  457. #endif
  458. osSemaphoreRelease(info->client.mutex);
  459. #ifdef BENCH_USE_NONBLOCK
  460. if (sz == 0)
  461. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  462. #endif
  463. return sz;
  464. }
  465. /* server recv callback */
  466. static int ServerMemRecv(info_t* info, char* buf, int sz)
  467. {
  468. #ifdef CMSIS_OS2_H_
  469. osSemaphoreAcquire(info->server.mutex, osWaitForever);
  470. #else
  471. osSemaphoreWait(info->server.mutex, osWaitForever);
  472. #endif
  473. #ifndef BENCH_USE_NONBLOCK
  474. while (info->to_server.write_idx - info->to_server.read_idx < sz &&
  475. !info->client.done) {
  476. osSemaphoreRelease(info->server.mutex);
  477. #ifdef CMSIS_OS2_H_
  478. if (osThreadFlagsWait(1, osFlagsWaitAny, RECV_WAIT_TIMEOUT) == osFlagsErrorTimeout) {
  479. printf("Server Recv: Timeout!\n");
  480. return WOLFSSL_CBIO_ERR_TIMEOUT;
  481. }
  482. osSemaphoreAcquire(info->server.mutex, osWaitForever);
  483. #else
  484. if (osSignalWait(1, RECV_WAIT_TIMEOUT).status == osEventTimeout) {
  485. printf("Server Recv: Timeout!\n");
  486. return WOLFSSL_CBIO_ERR_TIMEOUT;
  487. }
  488. osSemaphoreWait(info->server.mutex, osWaitForever);
  489. #endif
  490. }
  491. #else
  492. if (info->to_server.write_idx - info->to_server.read_idx < sz)
  493. sz = info->to_server.write_idx - info->to_server.read_idx;
  494. #endif
  495. XMEMCPY(buf, &info->to_server.buf[info->to_server.read_idx], sz);
  496. info->to_server.read_idx += sz;
  497. info->to_server.read_bytes += sz;
  498. /* if the rx has caught up with pending then reset buffer positions */
  499. if (info->to_server.read_bytes == info->to_server.write_bytes) {
  500. info->to_server.read_bytes = info->to_server.read_idx = 0;
  501. info->to_server.write_bytes = info->to_server.write_idx = 0;
  502. }
  503. if (info->showVerbose >= 2)
  504. printf("Server Recv: %d\n", sz);
  505. osSemaphoreRelease(info->server.mutex);
  506. #ifdef BENCH_USE_NONBLOCK
  507. if (sz == 0)
  508. return WOLFSSL_CBIO_ERR_WANT_READ;
  509. #endif
  510. return sz;
  511. }
  512. /* client send callback */
  513. static int ClientMemSend(info_t* info, char* buf, int sz)
  514. {
  515. #ifdef CMSIS_OS2_H_
  516. osSemaphoreAcquire(info->server.mutex, osWaitForever);
  517. #else
  518. osSemaphoreWait(info->server.mutex, osWaitForever);
  519. #endif
  520. #ifndef BENCH_USE_NONBLOCK
  521. /* check for overflow */
  522. if (info->to_server.write_idx + sz > MEM_BUFFER_SZ) {
  523. printf("ClientMemSend overflow %d %d %d\n",
  524. info->to_server.write_idx, sz, MEM_BUFFER_SZ);
  525. osSemaphoreRelease(info->server.mutex);
  526. return -1;
  527. }
  528. #else
  529. if (info->to_server.write_idx + sz > MEM_BUFFER_SZ)
  530. sz = MEM_BUFFER_SZ - info->to_server.write_idx;
  531. #endif
  532. if (info->showVerbose >= 2)
  533. printf("Client Send: %d\n", sz);
  534. XMEMCPY(&info->to_server.buf[info->to_server.write_idx], buf, sz);
  535. info->to_server.write_idx += sz;
  536. info->to_server.write_bytes += sz;
  537. #ifdef CMSIS_OS2_H_
  538. osThreadFlagsSet(info->server.threadId, 1);
  539. #else
  540. osSignalSet(info->server.threadId, 1);
  541. #endif
  542. osSemaphoreRelease(info->server.mutex);
  543. #ifdef BENCH_USE_NONBLOCK
  544. if (sz == 0)
  545. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  546. #endif
  547. return sz;
  548. }
  549. /* client recv callback */
  550. static int ClientMemRecv(info_t* info, char* buf, int sz)
  551. {
  552. #ifdef CMSIS_OS2_H_
  553. osSemaphoreAcquire(info->client.mutex, osWaitForever);
  554. #else
  555. osSemaphoreWait(info->client.mutex, osWaitForever);
  556. #endif
  557. #ifndef BENCH_USE_NONBLOCK
  558. while (info->to_client.write_idx - info->to_client.read_idx < sz &&
  559. !info->server.done) {
  560. osSemaphoreRelease(info->client.mutex);
  561. #ifdef CMSIS_OS2_H_
  562. if (osThreadFlagsWait(1, osFlagsWaitAny, RECV_WAIT_TIMEOUT) == osFlagsErrorTimeout) {
  563. printf("Client Recv: Timeout!\n");
  564. return WOLFSSL_CBIO_ERR_TIMEOUT;
  565. }
  566. osSemaphoreAcquire(info->client.mutex, osWaitForever);
  567. #else
  568. if (osSignalWait(1, RECV_WAIT_TIMEOUT).status == osEventTimeout) {
  569. printf("Client Recv: Timeout!\n");
  570. return WOLFSSL_CBIO_ERR_TIMEOUT;
  571. }
  572. osSemaphoreWait(info->client.mutex, osWaitForever);
  573. #endif
  574. }
  575. #else
  576. if (info->to_client.write_idx - info->to_client.read_idx < sz)
  577. sz = info->to_client.write_idx - info->to_client.read_idx;
  578. #endif
  579. XMEMCPY(buf, &info->to_client.buf[info->to_client.read_idx], sz);
  580. info->to_client.read_idx += sz;
  581. info->to_client.read_bytes += sz;
  582. /* if the rx has caught up with pending then reset buffer positions */
  583. if (info->to_client.read_bytes == info->to_client.write_bytes) {
  584. info->to_client.read_bytes = info->to_client.read_idx = 0;
  585. info->to_client.write_bytes = info->to_client.write_idx = 0;
  586. }
  587. if (info->showVerbose >= 2)
  588. printf("Client Recv: %d\n", sz);
  589. osSemaphoreRelease(info->client.mutex);
  590. #ifdef BENCH_USE_NONBLOCK
  591. if (sz == 0)
  592. return WOLFSSL_CBIO_ERR_WANT_READ;
  593. #endif
  594. return sz;
  595. }
  596. static int ServerSend(WOLFSSL* ssl, char* buf, int sz, void* ctx)
  597. {
  598. info_t* info = (info_t*)ctx;
  599. (void)ssl;
  600. return ServerMemSend(info, buf, sz);
  601. }
  602. static int ServerRecv(WOLFSSL* ssl, char* buf, int sz, void* ctx)
  603. {
  604. info_t* info = (info_t*)ctx;
  605. (void)ssl;
  606. return ServerMemRecv(info, buf, sz);
  607. }
  608. static int ClientSend(WOLFSSL* ssl, char* buf, int sz, void* ctx)
  609. {
  610. info_t* info = (info_t*)ctx;
  611. (void)ssl;
  612. return ClientMemSend(info, buf, sz);
  613. }
  614. static int ClientRecv(WOLFSSL* ssl, char* buf, int sz, void* ctx)
  615. {
  616. info_t* info = (info_t*)ctx;
  617. (void)ssl;
  618. return ClientMemRecv(info, buf, sz);
  619. }
  620. static int bench_tls_client(info_t* info)
  621. {
  622. byte *writeBuf = NULL, *readBuf = NULL;
  623. double start, total = 0;
  624. int ret = 0, readBufSz;
  625. WOLFSSL_CTX* cli_ctx = NULL;
  626. WOLFSSL* cli_ssl = NULL;
  627. int haveShownPeerInfo = 0;
  628. int tls13 = XSTRNCMP(info->cipher, "TLS13", 5) == 0;
  629. int total_sz;
  630. total = gettime_secs(0);
  631. /* set up client */
  632. #ifdef WOLFSSL_TLS13
  633. if (tls13) {
  634. #ifdef WOLFSSL_STATIC_MEMORY
  635. ret = wolfSSL_CTX_load_static_memory(&cli_ctx, wolfTLSv1_3_client_method_ex,
  636. gWolfCTXCli, sizeof(gWolfCTXCli), WOLFMEM_GENERAL , 10);
  637. #else
  638. cli_ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method());
  639. #endif
  640. }
  641. #endif
  642. if (!tls13) {
  643. #if !defined(WOLFSSL_TLS13)
  644. #ifdef WOLFSSL_STATIC_MEMORY
  645. ret = wolfSSL_CTX_load_static_memory(&cli_ctx, wolfSSLv23_client_method_ex,
  646. gWolfCTXCli, sizeof(gWolfCTXCli), WOLFMEM_GENERAL , 10);
  647. #else
  648. cli_ctx = wolfSSL_CTX_new(wolfSSLv23_client_method());
  649. #endif
  650. #elif !defined(WOLFSSL_NO_TLS12)
  651. #ifdef WOLFSSL_STATIC_MEMORY
  652. ret = wolfSSL_CTX_load_static_memory(&cli_ctx, wolfTLSv1_2_client_method_ex,
  653. gWolfCTXCli, sizeof(gWolfCTXCli), WOLFMEM_GENERAL , 10);
  654. #else
  655. cli_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  656. #endif
  657. #endif
  658. }
  659. if (cli_ctx == NULL || ret != 0) {
  660. printf("error creating ctx: ret %d\n", ret);
  661. ret = MEMORY_E; goto exit;
  662. }
  663. #ifdef WOLFSSL_STATIC_MEMORY
  664. ret = wolfSSL_CTX_load_static_memory(&cli_ctx, 0, gWolfIOCli, sizeof(gWolfIOCli),
  665. WOLFMEM_IO_POOL, 10 );
  666. #endif
  667. #ifndef NO_CERTS
  668. #ifdef HAVE_ECC
  669. if (XSTRSTR(info->cipher, "ECDSA")) {
  670. ret = wolfSSL_CTX_load_verify_buffer(cli_ctx, ca_ecc_cert_der_256,
  671. sizeof_ca_ecc_cert_der_256, WOLFSSL_FILETYPE_ASN1);
  672. }
  673. else
  674. #endif
  675. {
  676. ret = wolfSSL_CTX_load_verify_buffer(cli_ctx, ca_cert_der_2048,
  677. sizeof_ca_cert_der_2048, WOLFSSL_FILETYPE_ASN1);
  678. }
  679. if (ret != WOLFSSL_SUCCESS) {
  680. printf("error loading CA\n");
  681. goto exit;
  682. }
  683. #endif /* !NO_CERTS */
  684. wolfSSL_CTX_SetIOSend(cli_ctx, ClientSend);
  685. wolfSSL_CTX_SetIORecv(cli_ctx, ClientRecv);
  686. /* set cipher suite */
  687. ret = wolfSSL_CTX_set_cipher_list(cli_ctx, info->cipher);
  688. if (ret != WOLFSSL_SUCCESS) {
  689. printf("error setting cipher suite\n");
  690. goto exit;
  691. }
  692. #ifndef NO_DH
  693. ret = wolfSSL_CTX_SetMinDhKey_Sz(cli_ctx, MIN_DHKEY_BITS);
  694. if (ret != WOLFSSL_SUCCESS) {
  695. printf("Error setting minimum DH key size\n");
  696. goto exit;
  697. }
  698. #endif /* !NO_DH */
  699. /* Allocate and initialize a packet sized buffer */
  700. writeBuf = (unsigned char*)XMALLOC(info->packetSize, NULL,
  701. DYNAMIC_TYPE_TMP_BUFFER);
  702. if (writeBuf == NULL) {
  703. printf("failed to allocate write memory\n");
  704. ret = MEMORY_E; goto exit;
  705. }
  706. /* Allocate read buffer */
  707. readBufSz = info->packetSize;
  708. readBuf = (unsigned char*)XMALLOC(readBufSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  709. if (readBuf == NULL) {
  710. printf("failed to allocate read memory\n");
  711. ret = MEMORY_E; goto exit;
  712. }
  713. /* BENCHMARK CONNECTIONS LOOP */
  714. while (!info->client.shutdown) {
  715. int writeSz = info->packetSize;
  716. #ifdef BENCH_USE_NONBLOCK
  717. int err;
  718. #endif
  719. cli_ssl = wolfSSL_new(cli_ctx);
  720. if (cli_ssl == NULL) {
  721. printf("error creating client object\n");
  722. ret = MEMORY_E; goto exit;
  723. }
  724. wolfSSL_SetIOReadCtx(cli_ssl, info);
  725. wolfSSL_SetIOWriteCtx(cli_ssl, info);
  726. /* perform connect */
  727. start = gettime_secs(1);
  728. #ifndef BENCH_USE_NONBLOCK
  729. ret = wolfSSL_connect(cli_ssl);
  730. #else
  731. do
  732. {
  733. ret = wolfSSL_connect(cli_ssl);
  734. err = wolfSSL_get_error(cli_ssl, ret);
  735. }
  736. while (err == WOLFSSL_ERROR_WANT_READ || err == WOLFSSL_ERROR_WANT_WRITE);
  737. #endif
  738. start = gettime_secs(0) - start;
  739. if (ret != WOLFSSL_SUCCESS) {
  740. ret = wolfSSL_get_error(cli_ssl, ret);
  741. printf("error %d connecting client\n", ret);
  742. goto exit;
  743. }
  744. info->client_stats.connTime += start;
  745. info->client_stats.connCount++;
  746. if ((info->showPeerInfo) && (!haveShownPeerInfo)) {
  747. haveShownPeerInfo = 1;
  748. ShowPeer(cli_ssl);
  749. }
  750. /* check for run time completion and issue shutdown */
  751. if (gettime_secs(0) - total >= info->runTimeSec) {
  752. info->client.shutdown = 1;
  753. writeSz = (int)XSTRLEN(kShutdown) + 1;
  754. XMEMCPY(writeBuf, kShutdown, writeSz); /* include null term */
  755. if (info->showVerbose) {
  756. printf("Sending shutdown\n");
  757. }
  758. ret = wolfSSL_write(cli_ssl, writeBuf, writeSz);
  759. if (ret < 0) {
  760. ret = wolfSSL_get_error(cli_ssl, ret);
  761. printf("error %d on client write\n", ret);
  762. goto exit;
  763. }
  764. }
  765. else {
  766. XMEMSET(writeBuf, 0, info->packetSize);
  767. XSTRNCPY((char*)writeBuf, kTestStr, info->packetSize);
  768. }
  769. /* write / read echo loop */
  770. ret = 0;
  771. total_sz = 0;
  772. while (ret == 0 && total_sz < info->maxSize && !info->client.shutdown) {
  773. /* write test message to server */
  774. start = gettime_secs(1);
  775. #ifndef BENCH_USE_NONBLOCK
  776. ret = wolfSSL_write(cli_ssl, writeBuf, writeSz);
  777. #else
  778. do {
  779. ret = wolfSSL_write(cli_ssl, writeBuf, writeSz);
  780. err = wolfSSL_get_error(cli_ssl, ret);
  781. }
  782. while (err == WOLFSSL_ERROR_WANT_WRITE);
  783. #endif
  784. info->client_stats.txTime += gettime_secs(0) - start;
  785. if (ret < 0) {
  786. ret = wolfSSL_get_error(cli_ssl, ret);
  787. printf("error %d on client write\n", ret);
  788. goto exit;
  789. }
  790. info->client_stats.txTotal += ret;
  791. total_sz += ret;
  792. /* read echo of message from server */
  793. XMEMSET(readBuf, 0, readBufSz);
  794. start = gettime_secs(1);
  795. #ifndef BENCH_USE_NONBLOCK
  796. ret = wolfSSL_read(cli_ssl, readBuf, readBufSz);
  797. #else
  798. do {
  799. ret = wolfSSL_read(cli_ssl, readBuf, readBufSz);
  800. err = wolfSSL_get_error(cli_ssl, ret);
  801. }
  802. while (err == WOLFSSL_ERROR_WANT_READ);
  803. #endif
  804. info->client_stats.rxTime += gettime_secs(0) - start;
  805. if (ret < 0) {
  806. ret = wolfSSL_get_error(cli_ssl, ret);
  807. printf("error %d on client read\n", ret);
  808. goto exit;
  809. }
  810. info->client_stats.rxTotal += ret;
  811. ret = 0; /* reset return code */
  812. /* validate echo */
  813. if (XMEMCMP((char*)writeBuf, (char*)readBuf, writeSz) != 0) {
  814. printf("echo check failed!\n");
  815. goto exit;
  816. }
  817. }
  818. wolfSSL_free(cli_ssl);
  819. cli_ssl = NULL;
  820. }
  821. exit:
  822. if (ret != 0 && ret != WOLFSSL_SUCCESS) {
  823. info->doShutdown = 1;
  824. printf("Client Error: %d (%s)\n", ret,
  825. wolfSSL_ERR_reason_error_string(ret));
  826. }
  827. /* cleanup */
  828. if (cli_ssl != NULL)
  829. wolfSSL_free(cli_ssl);
  830. if (cli_ctx != NULL)
  831. wolfSSL_CTX_free(cli_ctx);
  832. XFREE(readBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  833. XFREE(writeBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  834. info->client.ret = ret;
  835. return ret;
  836. }
  837. #ifdef CMSIS_OS2_H_
  838. static void client_thread(void* args)
  839. #else
  840. static void client_thread(const void* args)
  841. #endif
  842. {
  843. int ret;
  844. info_t* info = (info_t*)args;
  845. #ifdef CMSIS_OS2_H_
  846. info->client.threadId = osThreadGetId();
  847. #endif
  848. do {
  849. ret = bench_tls_client(info);
  850. /* signal server */
  851. if (!info->server.done && info->server.threadId != 0) {
  852. #ifdef CMSIS_OS2_H_
  853. osThreadFlagsSet(info->server.threadId, 1);
  854. #else
  855. osSignalSet(info->server.threadId, 1);
  856. #endif
  857. }
  858. info->client.ret = ret;
  859. info->client.done = 1;
  860. osThreadSuspend(info->client.threadId);
  861. if (info->doShutdown)
  862. info->server.done = 1;
  863. } while (!info->doShutdown);
  864. osThreadTerminate(info->client.threadId);
  865. info->client.threadId = NULL;
  866. }
  867. static int bench_tls_server(info_t* info)
  868. {
  869. byte *readBuf = NULL;
  870. double start;
  871. int ret = 0, len = 0, readBufSz;
  872. WOLFSSL_CTX* srv_ctx = NULL;
  873. WOLFSSL* srv_ssl = NULL;
  874. int tls13 = XSTRNCMP(info->cipher, "TLS13", 5) == 0;
  875. int total_sz;
  876. /* set up server */
  877. #ifdef WOLFSSL_TLS13
  878. if (tls13) {
  879. #ifdef WOLFSSL_STATIC_MEMORY
  880. ret = wolfSSL_CTX_load_static_memory(&srv_ctx, wolfTLSv1_3_server_method_ex,
  881. gWolfCTXSrv, sizeof(gWolfCTXSrv), WOLFMEM_GENERAL , 10);
  882. #else
  883. srv_ctx = wolfSSL_CTX_new(wolfTLSv1_3_server_method());
  884. #endif
  885. }
  886. #endif
  887. if (!tls13) {
  888. #if !defined(WOLFSSL_TLS13)
  889. #ifdef WOLFSSL_STATIC_MEMORY
  890. ret = wolfSSL_CTX_load_static_memory(&srv_ctx, wolfSSLv23_server_method_ex,
  891. gWolfCTXSrv, sizeof(gWolfCTXSrv), WOLFMEM_GENERAL , 10);
  892. #else
  893. srv_ctx = wolfSSL_CTX_new(wolfSSLv23_server_method());
  894. #endif
  895. #elif !defined(WOLFSSL_NO_TLS12)
  896. #ifdef WOLFSSL_STATIC_MEMORY
  897. ret = wolfSSL_CTX_load_static_memory(&srv_ctx, wolfTLSv1_2_server_method_ex,
  898. gWolfCTXSrv, sizeof(gWolfCTXSrv), WOLFMEM_GENERAL , 10);
  899. #else
  900. srv_ctx = wolfSSL_CTX_new(wolfTLSv1_2_server_method());
  901. #endif
  902. #endif
  903. }
  904. if (srv_ctx == NULL || ret != 0) {
  905. printf("error creating server ctx: ret %d\n", ret);
  906. ret = MEMORY_E; goto exit;
  907. }
  908. #ifdef WOLFSSL_STATIC_MEMORY
  909. ret = wolfSSL_CTX_load_static_memory(&srv_ctx, 0, gWolfIOSrv, sizeof(gWolfIOSrv),
  910. WOLFMEM_IO_POOL, 10 );
  911. #endif
  912. #ifndef NO_CERTS
  913. #ifdef HAVE_ECC
  914. if (XSTRSTR(info->cipher, "ECDSA")) {
  915. ret = wolfSSL_CTX_use_PrivateKey_buffer(srv_ctx, ecc_key_der_256,
  916. sizeof_ecc_key_der_256, WOLFSSL_FILETYPE_ASN1);
  917. }
  918. else
  919. #endif
  920. {
  921. ret = wolfSSL_CTX_use_PrivateKey_buffer(srv_ctx, server_key_der_2048,
  922. sizeof_server_key_der_2048, WOLFSSL_FILETYPE_ASN1);
  923. }
  924. if (ret != WOLFSSL_SUCCESS) {
  925. printf("error loading server key\n");
  926. goto exit;
  927. }
  928. #ifdef HAVE_ECC
  929. if (XSTRSTR(info->cipher, "ECDSA")) {
  930. ret = wolfSSL_CTX_use_certificate_buffer(srv_ctx, serv_ecc_der_256,
  931. sizeof_serv_ecc_der_256, WOLFSSL_FILETYPE_ASN1);
  932. }
  933. else
  934. #endif
  935. {
  936. ret = wolfSSL_CTX_use_certificate_buffer(srv_ctx, server_cert_der_2048,
  937. sizeof_server_cert_der_2048, WOLFSSL_FILETYPE_ASN1);
  938. }
  939. if (ret != WOLFSSL_SUCCESS) {
  940. printf("error loading server cert\n");
  941. goto exit;
  942. }
  943. #endif /* !NO_CERTS */
  944. wolfSSL_CTX_SetIOSend(srv_ctx, ServerSend);
  945. wolfSSL_CTX_SetIORecv(srv_ctx, ServerRecv);
  946. /* set cipher suite */
  947. ret = wolfSSL_CTX_set_cipher_list(srv_ctx, info->cipher);
  948. if (ret != WOLFSSL_SUCCESS) {
  949. printf("error setting cipher suite\n");
  950. goto exit;
  951. }
  952. #ifndef NO_DH
  953. ret = wolfSSL_CTX_SetMinDhKey_Sz(srv_ctx, MIN_DHKEY_BITS);
  954. if (ret != WOLFSSL_SUCCESS) {
  955. printf("Error setting minimum DH key size\n");
  956. goto exit;
  957. }
  958. #endif
  959. /* Allocate read buffer */
  960. readBufSz = info->packetSize;
  961. readBuf = (unsigned char*)XMALLOC(readBufSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  962. if (readBuf == NULL) {
  963. printf("failed to allocate read memory\n");
  964. ret = MEMORY_E; goto exit;
  965. }
  966. /* BENCHMARK CONNECTIONS LOOP */
  967. while (!info->server.shutdown) {
  968. #ifdef BENCH_USE_NONBLOCK
  969. int err;
  970. #endif
  971. #ifdef BENCH_USE_NONBLOCK
  972. if (ret == -2) {
  973. osDelay(0);
  974. continue;
  975. }
  976. #endif
  977. srv_ssl = wolfSSL_new(srv_ctx);
  978. if (srv_ssl == NULL) {
  979. printf("error creating server object\n");
  980. ret = MEMORY_E; goto exit;
  981. }
  982. wolfSSL_SetIOReadCtx(srv_ssl, info);
  983. wolfSSL_SetIOWriteCtx(srv_ssl, info);
  984. #ifndef NO_DH
  985. wolfSSL_SetTmpDH(srv_ssl, p, sizeof(p), g, sizeof(g));
  986. #endif
  987. /* accept TLS connection */
  988. start = gettime_secs(1);
  989. #ifndef BENCH_USE_NONBLOCK
  990. ret = wolfSSL_accept(srv_ssl);
  991. #else
  992. do {
  993. ret = wolfSSL_accept(srv_ssl);
  994. err = wolfSSL_get_error(srv_ssl, ret);
  995. }
  996. while (err == WOLFSSL_ERROR_WANT_READ || err == WOLFSSL_ERROR_WANT_WRITE);
  997. #endif
  998. start = gettime_secs(0) - start;
  999. if (ret != WOLFSSL_SUCCESS) {
  1000. ret = wolfSSL_get_error(srv_ssl, ret);
  1001. printf("error %d on server accept\n", ret);
  1002. goto exit;
  1003. }
  1004. info->server_stats.connTime += start;
  1005. info->server_stats.connCount++;
  1006. /* echo loop */
  1007. ret = 0;
  1008. total_sz = 0;
  1009. while (ret == 0 && total_sz < info->maxSize) {
  1010. double rxTime;
  1011. /* read message from client */
  1012. XMEMSET(readBuf, 0, readBufSz);
  1013. start = gettime_secs(1);
  1014. #ifndef BENCH_USE_NONBLOCK
  1015. ret = wolfSSL_read(srv_ssl, readBuf, readBufSz);
  1016. #else
  1017. do {
  1018. ret = wolfSSL_read(srv_ssl, readBuf, readBufSz);
  1019. err = wolfSSL_get_error(srv_ssl, ret);
  1020. }
  1021. while (err == WOLFSSL_ERROR_WANT_READ);
  1022. #endif
  1023. rxTime = gettime_secs(0) - start;
  1024. /* shutdown signals, no more connections for this cipher */
  1025. if (XSTRSTR((const char*)readBuf, kShutdown) != NULL) {
  1026. info->server.shutdown = 1;
  1027. if (info->showVerbose) {
  1028. printf("Server shutdown done\n");
  1029. }
  1030. ret = 0; /* success */
  1031. break;
  1032. }
  1033. info->server_stats.rxTime += rxTime;
  1034. if (ret < 0) {
  1035. ret = wolfSSL_get_error(srv_ssl, ret);
  1036. printf("error %d on server read\n", ret);
  1037. goto exit;
  1038. }
  1039. info->server_stats.rxTotal += ret;
  1040. len = ret;
  1041. total_sz += ret;
  1042. /* write message back to client */
  1043. start = gettime_secs(1);
  1044. #ifndef BENCH_USE_NONBLOCK
  1045. ret = wolfSSL_write(srv_ssl, readBuf, len);
  1046. #else
  1047. do {
  1048. ret = wolfSSL_write(srv_ssl, readBuf, len);
  1049. err = wolfSSL_get_error(srv_ssl, ret);
  1050. }
  1051. while (err == WOLFSSL_ERROR_WANT_WRITE);
  1052. #endif
  1053. info->server_stats.txTime += gettime_secs(0) - start;
  1054. if (ret < 0) {
  1055. ret = wolfSSL_get_error(srv_ssl, ret);
  1056. printf("error %d on server write\n", ret);
  1057. goto exit;
  1058. }
  1059. info->server_stats.txTotal += ret;
  1060. ret = 0; /* reset return code */
  1061. }
  1062. wolfSSL_free(srv_ssl);
  1063. srv_ssl = NULL;
  1064. }
  1065. exit:
  1066. if (ret != 0 && ret != WOLFSSL_SUCCESS) {
  1067. info->doShutdown = 1;
  1068. printf("Server Error: %d (%s)\n", ret,
  1069. wolfSSL_ERR_reason_error_string(ret));
  1070. }
  1071. /* clean up */
  1072. if (srv_ssl != NULL)
  1073. wolfSSL_free(srv_ssl);
  1074. if (srv_ctx != NULL)
  1075. wolfSSL_CTX_free(srv_ctx);
  1076. XFREE(readBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1077. info->server.ret = ret;
  1078. return ret;
  1079. }
  1080. #ifdef CMSIS_OS2_H_
  1081. static void server_thread(void* args)
  1082. #else
  1083. static void server_thread(const void* args)
  1084. #endif
  1085. {
  1086. int ret;
  1087. info_t* info = (info_t*)args;
  1088. #ifdef CMSIS_OS2_H_
  1089. info->server.threadId = osThreadGetId();
  1090. #endif
  1091. do {
  1092. ret = bench_tls_server(info);
  1093. /* signal client */
  1094. if (!info->client.done && info->client.threadId != 0) {
  1095. #ifdef CMSIS_OS2_H_
  1096. osThreadFlagsSet(info->client.threadId, 1);
  1097. #else
  1098. osSignalSet(info->client.threadId, 1);
  1099. #endif
  1100. }
  1101. info->server.ret = ret;
  1102. info->server.done = 1;
  1103. osThreadSuspend(info->server.threadId);
  1104. if (info->doShutdown)
  1105. info->client.done = 1;
  1106. } while (!info->doShutdown);
  1107. osThreadTerminate(info->server.threadId);
  1108. info->server.threadId = NULL;
  1109. }
  1110. #ifdef CMSIS_OS2_H_
  1111. static const osThreadAttr_t server_thread_attributes = {
  1112. .name = "server_thread",
  1113. .priority = (osPriority_t) osPriorityNormal,
  1114. .stack_size = WOLF_EXAMPLES_STACK
  1115. };
  1116. static const osThreadAttr_t client_thread_attributes = {
  1117. .name = "client_thread",
  1118. .priority = (osPriority_t) osPriorityNormal,
  1119. .stack_size = WOLF_EXAMPLES_STACK
  1120. };
  1121. #endif
  1122. int bench_tls(void* args)
  1123. {
  1124. int ret = 0;
  1125. info_t *info = NULL;
  1126. char *cipher, *next_cipher, *ciphers;
  1127. /* Runtime variables */
  1128. int argRuntimeSec = BENCH_RUNTIME_SEC;
  1129. int argTestPacketSize = TEST_PACKET_SIZE;
  1130. int argTestMaxSize = TEST_MAX_SIZE;
  1131. int argShowVerbose = SHOW_VERBOSE;
  1132. const char* argHost = BENCH_DEFAULT_HOST;
  1133. int argPort = BENCH_DEFAULT_PORT;
  1134. int argShowPeerInfo = BENCH_SHOW_PEER_INFO;
  1135. #ifdef DEBUG_WOLFSSL
  1136. if (argShowVerbose >= 3) {
  1137. wolfSSL_Debugging_ON();
  1138. }
  1139. else {
  1140. wolfSSL_Debugging_OFF();
  1141. }
  1142. #endif
  1143. #ifdef TEST_CIPHER_SUITE
  1144. ciphers = TEST_CIPHER_SUITE;
  1145. #else
  1146. /* Get cipher suite list */
  1147. ciphers = (char*)XMALLOC(WOLFSSL_CIPHER_LIST_MAX_SIZE, NULL,
  1148. DYNAMIC_TYPE_TMP_BUFFER);
  1149. if (ciphers == NULL) {
  1150. ret = MEMORY_E; goto exit;
  1151. }
  1152. wolfSSL_get_ciphers(ciphers, WOLFSSL_CIPHER_LIST_MAX_SIZE);
  1153. #endif
  1154. cipher = ciphers;
  1155. /* Allocate test info */
  1156. info = (info_t*)XMALLOC(sizeof(info_t), NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1157. if (info == NULL) {
  1158. ret = MEMORY_E; goto exit;
  1159. }
  1160. XMEMSET(info, 0, sizeof(info_t));
  1161. info->host = argHost;
  1162. info->port = argPort;
  1163. info->packetSize = argTestPacketSize;
  1164. info->runTimeSec = argRuntimeSec;
  1165. info->maxSize = argTestMaxSize;
  1166. info->showPeerInfo = argShowPeerInfo;
  1167. info->showVerbose = argShowVerbose;
  1168. #ifdef CMSIS_OS2_H_
  1169. info->server.mutex = osSemaphoreNew(1, 0, NULL);
  1170. info->client.mutex = osSemaphoreNew(1, 0, NULL);
  1171. #else
  1172. info->server.mutex = osSemaphoreCreate(&info->server.mutexDef, 1);
  1173. info->client.mutex = osSemaphoreCreate(&info->client.mutexDef, 1);
  1174. /* threads */
  1175. info->server.threadDef.name = "server_thread";
  1176. info->server.threadDef.pthread = server_thread;
  1177. info->server.threadDef.tpriority = osPriorityNormal;
  1178. info->server.threadDef.stacksize = WOLF_EXAMPLES_STACK;
  1179. info->client.threadDef.name = "client_thread";
  1180. info->client.threadDef.pthread = client_thread;
  1181. info->client.threadDef.tpriority = osPriorityNormal;
  1182. info->client.threadDef.stacksize = WOLF_EXAMPLES_STACK;
  1183. #endif
  1184. /* parse by : */
  1185. while ((cipher != NULL) && (cipher[0] != '\0')) {
  1186. next_cipher = strchr(cipher, ':');
  1187. if (next_cipher != NULL) {
  1188. cipher[next_cipher - cipher] = '\0';
  1189. }
  1190. if (argShowVerbose) {
  1191. printf("Cipher: %s\n", cipher);
  1192. }
  1193. /* set cipher suite */
  1194. info->cipher = cipher;
  1195. /* reset thread info */
  1196. info->server.ret = info->client.ret = 0;
  1197. info->server.done = info->client.done = 0;
  1198. info->server.shutdown = info->client.shutdown = 0;
  1199. XMEMSET(&info->server_stats, 0, sizeof(info->server_stats));
  1200. XMEMSET(&info->client_stats, 0, sizeof(info->client_stats));
  1201. XMEMSET(&info->to_server, 0, sizeof(info->to_server));
  1202. XMEMSET(&info->to_client, 0, sizeof(info->to_client));
  1203. /* make sure nothing is locking it */
  1204. osSemaphoreRelease(info->server.mutex);
  1205. osSemaphoreRelease(info->client.mutex);
  1206. /* start threads */
  1207. if (info->server.threadId == 0) {
  1208. #ifdef CMSIS_OS2_H_
  1209. osThreadNew(server_thread, info, &server_thread_attributes);
  1210. #else
  1211. info->server.threadId = osThreadCreate(&info->server.threadDef, info);
  1212. #endif
  1213. }
  1214. else {
  1215. osThreadResume(info->server.threadId);
  1216. }
  1217. if (info->client.threadId == 0) {
  1218. #ifdef CMSIS_OS2_H_
  1219. osThreadNew(client_thread, info, &client_thread_attributes);
  1220. #else
  1221. info->client.threadId = osThreadCreate(&info->client.threadDef, info);
  1222. #endif
  1223. }
  1224. else {
  1225. osThreadResume(info->client.threadId);
  1226. }
  1227. /* Wait until threads are marked done */
  1228. while (!info->client.done || !info->server.done) {
  1229. osThreadYield(); /* Allow other threads to run */
  1230. }
  1231. if (argShowVerbose) {
  1232. /* print results */
  1233. PrintTlsStats(&info->server_stats, "Server", info->cipher, 1);
  1234. PrintTlsStats(&info->client_stats, "Client", info->cipher, 1);
  1235. }
  1236. printf("%-6s %-33s %11s %9s %9s %9s %9s %9s %17s %15s\n",
  1237. "Side", "Cipher", "Total Bytes", "Num Conns", "Rx ms", "Tx ms",
  1238. "Rx MB/s", "Tx MB/s", "Connect Total ms", "Connect Avg ms");
  1239. PrintTlsStats(&info->server_stats, "Server", info->cipher, 0);
  1240. PrintTlsStats(&info->client_stats, "Client", info->cipher, 0);
  1241. PrintMemStats();
  1242. /* target next cipher */
  1243. cipher = (next_cipher != NULL) ? (next_cipher + 1) : NULL;
  1244. } /* while */
  1245. /* do thread shutdown */
  1246. info->doShutdown = 1;
  1247. info->server.done = 0;
  1248. info->client.done = 0;
  1249. osThreadResume(info->server.threadId);
  1250. osThreadResume(info->client.threadId);
  1251. /* Wait until threads are marked done */
  1252. while (!info->client.done || !info->server.done) {
  1253. osThreadYield(); /* Allow other threads to run */
  1254. }
  1255. exit:
  1256. /* cleanup thread info */
  1257. osSemaphoreDelete(info->server.mutex);
  1258. osSemaphoreDelete(info->client.mutex);
  1259. XFREE(info, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1260. #ifndef TEST_CIPHER_SUITE
  1261. /* Free cipher list */
  1262. XFREE(ciphers, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1263. #endif
  1264. /* set return code */
  1265. if (args)
  1266. ((func_args*)args)->return_code = ret;
  1267. return ret;
  1268. }
  1269. #endif /* (!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) && !WOLFCRYPT_ONLY && !SINGLE_THREADED */
  1270. #ifndef WOLFCRYPT_ONLY
  1271. static void ShowCiphers(void)
  1272. {
  1273. int ret;
  1274. char* ciphers = (char*)XMALLOC(WOLFSSL_CIPHER_LIST_MAX_SIZE, NULL,
  1275. DYNAMIC_TYPE_TMP_BUFFER);
  1276. if (ciphers) {
  1277. ret = wolfSSL_get_ciphers(ciphers, WOLFSSL_CIPHER_LIST_MAX_SIZE);
  1278. if (ret == WOLFSSL_SUCCESS)
  1279. printf("%s\n", ciphers);
  1280. XFREE(ciphers, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1281. }
  1282. }
  1283. #endif
  1284. static void PrintMemStats(void)
  1285. {
  1286. #ifdef WOLFSSL_DEBUG_MEMORY
  1287. printf("\nHeap MinEver %d, Free %d, Stack %lu\n",
  1288. xPortGetMinimumEverFreeHeapSize(),
  1289. xPortGetFreeHeapSize(),
  1290. uxTaskGetStackHighWaterMark(NULL));
  1291. #endif
  1292. }
  1293. #if !defined(WOLFCRYPT_ONLY) && defined(WOLFSSL_TLS13) && !defined(NO_TLS_UART_TEST)
  1294. /* UART DMA IO Routines */
  1295. #ifndef B115200
  1296. #define B115200 115200
  1297. #endif
  1298. /* Max buffer for a single TLS frame */
  1299. #ifndef MAX_RECORD_SIZE
  1300. #define MAX_RECORD_SIZE (16 * 1024)
  1301. #endif
  1302. typedef struct {
  1303. int curr_index;
  1304. int data_len;
  1305. char buf[MAX_RECORD_SIZE];
  1306. } tls13_buf;
  1307. /* This sets which UART to do the TLS 1.3 connection over. It is something you
  1308. * will have to configure in STMCubeIDE and then change here. */
  1309. #ifndef TLS_UART
  1310. #define TLS_UART huart2
  1311. #endif
  1312. extern UART_HandleTypeDef TLS_UART;
  1313. static int msg_length = 0;
  1314. void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size) {
  1315. if (huart->Instance == TLS_UART.Instance) {
  1316. msg_length = Size;
  1317. }
  1318. }
  1319. static int uartIORx(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  1320. {
  1321. HAL_StatusTypeDef status;
  1322. tls13_buf *tb = ctx;
  1323. #ifdef DEBUG_UART_IO
  1324. printf("UART Read: In %d\n", sz);
  1325. #endif
  1326. if (tb->curr_index + sz <= tb->data_len) {
  1327. XMEMCPY(buf, tb->buf + tb->curr_index, sz);
  1328. tb->curr_index += sz;
  1329. #ifdef DEBUG_UART_IO
  1330. printf("UART Read1: Out %d\n", sz);
  1331. #endif
  1332. return sz;
  1333. }
  1334. msg_length = 0;
  1335. XMEMSET(tb, 0, sizeof(*tb));
  1336. /* Now setup the DMA RX. */
  1337. status = HAL_UARTEx_ReceiveToIdle_DMA(&TLS_UART, (uint8_t *)tb->buf, MAX_RECORD_SIZE);
  1338. if (status != HAL_OK) {
  1339. return WOLFSSL_CBIO_ERR_WANT_READ;
  1340. } else {
  1341. /* We now go into an infinite loop waiting for msg_length to be set to a
  1342. * value other than 0. This will be done when the other side writes to
  1343. * UART and then idles. That will trigger HAL_UARTEx_RxEventCallback()
  1344. * which will set msg_length to the length of data written.
  1345. *
  1346. * If you mistakenly get stuck here, please simply reset the board.
  1347. */
  1348. while(msg_length == 0) {
  1349. HAL_Delay(10);
  1350. }
  1351. #ifdef DEBUG_UART_IO
  1352. printf("Message received! length = %d\n", msg_length);
  1353. #endif
  1354. }
  1355. /* now return the number of bytes requested. */
  1356. XMEMCPY(buf, tb->buf, sz);
  1357. tb->data_len = msg_length;
  1358. tb->curr_index = sz;
  1359. #ifdef DEBUG_UART_IO
  1360. printf("UART Read2: Out %d\n", tb->data_len);
  1361. #endif
  1362. return sz;
  1363. }
  1364. static int uartIOTx(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  1365. {
  1366. HAL_StatusTypeDef status;
  1367. int ret = sz;
  1368. (void)ctx;
  1369. #ifdef DEBUG_UART_IO
  1370. printf("UART Write: In %d\n", sz);
  1371. #endif
  1372. status = HAL_UART_Transmit(&TLS_UART, (uint8_t *)buf, sz, 0xFFFF);
  1373. if (status != HAL_OK) {
  1374. ret = WOLFSSL_CBIO_ERR_WANT_WRITE;
  1375. }
  1376. #ifdef DEBUG_UART_IO
  1377. printf("UART Write: Out %d\n", ret);
  1378. #endif
  1379. return ret;
  1380. }
  1381. /* UART TLS 1.3 client and server */
  1382. #ifndef NO_WOLFSSL_SERVER
  1383. static int tls13_uart_server(void)
  1384. {
  1385. int ret = -1, err;
  1386. WOLFSSL_CTX* ctx = NULL;
  1387. WOLFSSL* ssl = NULL;
  1388. byte echoBuffer[100];
  1389. #ifdef WOLFSSL_SMALL_STACK
  1390. tls13_buf *tbuf = (tls13_buf *) XMALLOC(sizeof(*tbuf), NULL,
  1391. DYNAMIC_TYPE_TMP_BUFFER);
  1392. if (tbuf == NULL) {
  1393. printf("Memory allocation error\n");
  1394. goto done;
  1395. }
  1396. #else
  1397. tls13_buf tbuf[1];
  1398. #endif
  1399. XMEMSET(tbuf, 0, sizeof(*tbuf));
  1400. ctx = wolfSSL_CTX_new(wolfTLSv1_3_server_method());
  1401. if (ctx == NULL) {
  1402. printf("Error creating WOLFSSL_CTX\n");
  1403. goto done;
  1404. }
  1405. /* Register wolfSSL send/recv callbacks */
  1406. wolfSSL_CTX_SetIOSend(ctx, uartIOTx);
  1407. wolfSSL_CTX_SetIORecv(ctx, uartIORx);
  1408. ret = wolfSSL_CTX_use_PrivateKey_buffer(ctx, ecc_key_der_256,
  1409. sizeof_ecc_key_der_256, WOLFSSL_FILETYPE_ASN1);
  1410. if (ret != WOLFSSL_SUCCESS) {
  1411. printf("error loading server private key\n");
  1412. goto done;
  1413. }
  1414. ret = wolfSSL_CTX_use_certificate_buffer(ctx, serv_ecc_der_256,
  1415. sizeof_serv_ecc_der_256, WOLFSSL_FILETYPE_ASN1);
  1416. if (ret != WOLFSSL_SUCCESS) {
  1417. printf("error loading server certificate\n");
  1418. goto done;
  1419. }
  1420. ssl = wolfSSL_new(ctx);
  1421. if (ssl == NULL) {
  1422. printf("Error creating WOLFSSL\n");
  1423. goto done;
  1424. }
  1425. wolfSSL_SetIOReadCtx(ssl, tbuf);
  1426. printf("Waiting for client\n");
  1427. do {
  1428. ret = wolfSSL_accept(ssl);
  1429. err = wolfSSL_get_error(ssl, ret);
  1430. } while (err == WOLFSSL_ERROR_WANT_READ || err == WOLFSSL_ERROR_WANT_WRITE);
  1431. if (ret != WOLFSSL_SUCCESS) {
  1432. printf("TLS accept error %d\n", err);
  1433. goto done;
  1434. }
  1435. printf("TLS Accept handshake done\n");
  1436. /* Waiting for data to echo */
  1437. XMEMSET(echoBuffer, 0, sizeof(echoBuffer));
  1438. do {
  1439. ret = wolfSSL_read(ssl, echoBuffer, sizeof(echoBuffer)-1);
  1440. err = wolfSSL_get_error(ssl, ret);
  1441. } while (err == WOLFSSL_ERROR_WANT_READ || err == WOLFSSL_ERROR_WANT_WRITE);
  1442. printf("Read (%d): %s\n", err, echoBuffer);
  1443. do {
  1444. ret = wolfSSL_write(ssl, echoBuffer, XSTRLEN((char*)echoBuffer));
  1445. err = wolfSSL_get_error(ssl, ret);
  1446. } while (err == WOLFSSL_ERROR_WANT_READ || err == WOLFSSL_ERROR_WANT_WRITE);
  1447. printf("Sent (%d): %s\n", err, echoBuffer);
  1448. ret = 0; /* Success */
  1449. done:
  1450. if (ssl) {
  1451. wolfSSL_shutdown(ssl);
  1452. wolfSSL_free(ssl);
  1453. }
  1454. if (ctx) {
  1455. wolfSSL_CTX_free(ctx);
  1456. }
  1457. #ifdef WOLFSSL_SMALL_STACK
  1458. if (tbuf != NULL) {
  1459. XFREE(tbuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1460. }
  1461. #endif
  1462. return ret;
  1463. }
  1464. #endif
  1465. #ifndef NO_WOLFSSL_CLIENT
  1466. static int tls13_uart_client(void)
  1467. {
  1468. int ret = -1, err;
  1469. WOLFSSL_CTX* ctx = NULL;
  1470. WOLFSSL* ssl = NULL;
  1471. const char testStr[] = "Testing 1, 2 and 3\r\n";
  1472. byte readBuf[100];
  1473. #ifdef WOLFSSL_SMALL_STACK
  1474. tls13_buf *tbuf = (tls13_buf *) XMALLOC(sizeof(*tbuf), NULL,
  1475. DYNAMIC_TYPE_TMP_BUFFER);
  1476. if (tbuf == NULL) {
  1477. printf("Memory allocation error\n");
  1478. goto done;
  1479. }
  1480. #else
  1481. tls13_buf tbuf[1];
  1482. #endif
  1483. XMEMSET(tbuf, 0, sizeof(*tbuf));
  1484. ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method());
  1485. if (ctx == NULL) {
  1486. printf("Error creating WOLFSSL_CTX\n");
  1487. goto done;
  1488. }
  1489. /* Register wolfSSL send/recv callbacks */
  1490. wolfSSL_CTX_SetIOSend(ctx, uartIOTx);
  1491. wolfSSL_CTX_SetIORecv(ctx, uartIORx);
  1492. /* Load the root certificate. */
  1493. wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
  1494. ssl = wolfSSL_new(ctx);
  1495. if (ssl == NULL) {
  1496. printf("Error creating WOLFSSL\n");
  1497. goto done;
  1498. }
  1499. wolfSSL_SetIOReadCtx(ssl, tbuf);
  1500. #ifdef HAVE_PQC
  1501. if (wolfSSL_UseKeyShare(ssl, WOLFSSL_KYBER_LEVEL1) != WOLFSSL_SUCCESS) {
  1502. printf("wolfSSL_UseKeyShare Error!!");
  1503. }
  1504. #endif
  1505. do {
  1506. ret = wolfSSL_connect(ssl);
  1507. err = wolfSSL_get_error(ssl, ret);
  1508. } while (err == WOLFSSL_ERROR_WANT_READ || err == WOLFSSL_ERROR_WANT_WRITE);
  1509. if (ret != WOLFSSL_SUCCESS) {
  1510. printf("TLS connect error %d\n", err);
  1511. goto done;
  1512. }
  1513. printf("TLS Connect handshake done\n");
  1514. printf("Sending test string\n");
  1515. do {
  1516. ret = wolfSSL_write(ssl, testStr, XSTRLEN(testStr));
  1517. err = wolfSSL_get_error(ssl, ret);
  1518. } while (err == WOLFSSL_ERROR_WANT_READ || err == WOLFSSL_ERROR_WANT_WRITE);
  1519. printf("Sent (%d): %s\n", err, testStr);
  1520. XMEMSET(readBuf, 0, sizeof(readBuf));
  1521. do {
  1522. ret = wolfSSL_read(ssl, readBuf, sizeof(readBuf)-1);
  1523. err = wolfSSL_get_error(ssl, ret);
  1524. } while (err == WOLFSSL_ERROR_WANT_READ || err == WOLFSSL_ERROR_WANT_WRITE);
  1525. printf("Read (%d): %s\n", err, readBuf);
  1526. ret = 0; /* Success */
  1527. done:
  1528. if (ssl) {
  1529. wolfSSL_shutdown(ssl);
  1530. wolfSSL_free(ssl);
  1531. }
  1532. if (ctx) {
  1533. wolfSSL_CTX_free(ctx);
  1534. }
  1535. #ifdef WOLFSSL_SMALL_STACK
  1536. if (tbuf != NULL) {
  1537. XFREE(tbuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1538. }
  1539. #endif
  1540. return ret;
  1541. }
  1542. #endif
  1543. #endif /* !WOLFCRYPT_ONLY && WOLFSSL_TLS13 && !NO_TLS_UART_TEST */
  1544. /*****************************************************************************
  1545. * Public functions
  1546. ****************************************************************************/
  1547. #ifdef HAL_RTC_MODULE_ENABLED
  1548. extern RTC_HandleTypeDef hrtc;
  1549. double current_time(void)
  1550. {
  1551. RTC_TimeTypeDef time;
  1552. RTC_DateTypeDef date;
  1553. uint32_t subsec = 0;
  1554. /* must get time and date here due to STM32 HW bug */
  1555. HAL_RTC_GetTime(&hrtc, &time, FORMAT_BIN);
  1556. HAL_RTC_GetDate(&hrtc, &date, FORMAT_BIN);
  1557. /* Not all STM32 RTCs have subseconds in the struct */
  1558. #ifdef RTC_ALARMSUBSECONDMASK_ALL
  1559. subsec = (255 - time.SubSeconds) * 1000 / 255;
  1560. #endif
  1561. (void) date;
  1562. /* return seconds.milliseconds */
  1563. return ((double) time.Hours * 24) + ((double) time.Minutes * 60)
  1564. + (double) time.Seconds + ((double) subsec / 1000);
  1565. }
  1566. #endif /* HAL_RTC_MODULE_ENABLED */
  1567. #ifdef CMSIS_OS2_H_
  1568. void wolfCryptDemo(void* argument)
  1569. #else
  1570. void wolfCryptDemo(const void* argument)
  1571. #endif
  1572. {
  1573. HAL_StatusTypeDef halRet;
  1574. uint8_t buffer[2];
  1575. func_args args;
  1576. #ifdef DEBUG_WOLFSSL
  1577. wolfSSL_Debugging_ON();
  1578. #endif
  1579. /* initialize wolfSSL */
  1580. #ifdef WOLFCRYPT_ONLY
  1581. wolfCrypt_Init();
  1582. #else
  1583. wolfSSL_Init();
  1584. #endif
  1585. #ifdef WOLFSSL_STATIC_MEMORY
  1586. if (wc_LoadStaticMemory(&HEAP_HINT, gWolfMem, sizeof(gWolfMem),
  1587. WOLFMEM_GENERAL, 10) != 0) {
  1588. printf("unable to load static memory");
  1589. }
  1590. #endif
  1591. //wolfSSL_SetAllocators(wolfMallocCb, wolfFreeCb, wolfReallocCb);
  1592. while (1) {
  1593. memset(&args, 0, sizeof(args));
  1594. args.return_code = NOT_COMPILED_IN; /* default */
  1595. printf("\n\t\t\t\tMENU\n");
  1596. printf(menu1);
  1597. printf("Please select one of the above options:\n");
  1598. do {
  1599. halRet = HAL_UART_Receive(&HAL_CONSOLE_UART, buffer, sizeof(buffer), 100);
  1600. } while (halRet != HAL_OK || buffer[0] == '\n' || buffer[0] == '\r');
  1601. switch (buffer[0]) {
  1602. case 't':
  1603. printf("Running wolfCrypt Tests...\n");
  1604. #ifndef NO_CRYPT_TEST
  1605. args.return_code = 0;
  1606. wolfcrypt_test(&args);
  1607. #else
  1608. args.return_code = NOT_COMPILED_IN;
  1609. #endif
  1610. printf("Crypt Test: Return code %d\n", args.return_code);
  1611. break;
  1612. case 'b':
  1613. printf("Running wolfCrypt Benchmarks...\n");
  1614. #ifndef NO_CRYPT_BENCHMARK
  1615. args.return_code = 0;
  1616. benchmark_test(&args);
  1617. #else
  1618. args.return_code = NOT_COMPILED_IN;
  1619. #endif
  1620. printf("Benchmark Test: Return code %d\n", args.return_code);
  1621. break;
  1622. case 'l':
  1623. printf("Running TLS Benchmarks...\n");
  1624. #if (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER)) && !defined(WOLFCRYPT_ONLY) && !defined(SINGLE_THREADED)
  1625. bench_tls(&args);
  1626. #else
  1627. args.return_code = NOT_COMPILED_IN;
  1628. #endif
  1629. printf("TLS Benchmarks: Return code %d\n", args.return_code);
  1630. break;
  1631. case 'e':
  1632. #ifndef WOLFCRYPT_ONLY
  1633. ShowCiphers();
  1634. #else
  1635. printf("Not compiled in\n");
  1636. #endif
  1637. break;
  1638. #if !defined(WOLFCRYPT_ONLY) && defined(WOLFSSL_TLS13) && !defined(NO_TLS_UART_TEST)
  1639. case 's':
  1640. #if !defined(NO_WOLFSSL_SERVER)
  1641. printf("Running TLS 1.3 server...\n");
  1642. args.return_code = tls13_uart_server();
  1643. #else
  1644. args.return_code = NOT_COMPILED_IN;
  1645. #endif
  1646. printf("TLS 1.3 Server: Return code %d\n", args.return_code);
  1647. break;
  1648. case 'c':
  1649. #if !defined(NO_WOLFSSL_CLIENT)
  1650. printf("Running TLS 1.3 client...\n");
  1651. args.return_code = tls13_uart_client();
  1652. #else
  1653. args.return_code = NOT_COMPILED_IN;
  1654. #endif
  1655. printf("TLS 1.3 Client: Return code %d\n", args.return_code);
  1656. break;
  1657. #endif
  1658. // All other cases go here
  1659. default:
  1660. printf("\nSelection out of range\n");
  1661. break;
  1662. }
  1663. PrintMemStats();
  1664. }
  1665. #ifdef WOLFCRYPT_ONLY
  1666. wolfCrypt_Cleanup();
  1667. #else
  1668. wolfSSL_Cleanup();
  1669. #endif
  1670. }