test.h 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505
  1. /* test.h */
  2. #ifndef wolfSSL_TEST_H
  3. #define wolfSSL_TEST_H
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <assert.h>
  7. #include <ctype.h>
  8. #include <wolfssl/wolfcrypt/types.h>
  9. #include <wolfssl/wolfcrypt/error-crypt.h>
  10. #include <wolfssl/wolfcrypt/random.h>
  11. #include <wolfssl/wolfcrypt/mem_track.h>
  12. #if defined(OPENSSL_EXTRA) && defined(SHOW_CERTS)
  13. #include <wolfssl/openssl/ssl.h> /* for domain component NID value */
  14. #endif
  15. #ifdef ATOMIC_USER
  16. #include <wolfssl/wolfcrypt/aes.h>
  17. #include <wolfssl/wolfcrypt/arc4.h>
  18. #include <wolfssl/wolfcrypt/hmac.h>
  19. #endif
  20. #ifdef HAVE_PK_CALLBACKS
  21. #include <wolfssl/wolfcrypt/asn.h>
  22. #ifndef NO_RSA
  23. #include <wolfssl/wolfcrypt/rsa.h>
  24. #endif
  25. #ifdef HAVE_ECC
  26. #include <wolfssl/wolfcrypt/ecc.h>
  27. #endif /* HAVE_ECC */
  28. #ifndef NO_DH
  29. #include <wolfssl/wolfcrypt/dh.h>
  30. #endif /* !NO_DH */
  31. #ifdef HAVE_ED25519
  32. #include <wolfssl/wolfcrypt/ed25519.h>
  33. #endif /* HAVE_ED25519 */
  34. #ifdef HAVE_CURVE25519
  35. #include <wolfssl/wolfcrypt/curve25519.h>
  36. #endif /* HAVE_ECC */
  37. #endif /*HAVE_PK_CALLBACKS */
  38. #ifdef USE_WINDOWS_API
  39. #include <winsock2.h>
  40. #include <process.h>
  41. #ifdef TEST_IPV6 /* don't require newer SDK for IPV4 */
  42. #include <ws2tcpip.h>
  43. #include <wspiapi.h>
  44. #endif
  45. #define SOCKET_T SOCKET
  46. #define SNPRINTF _snprintf
  47. #elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
  48. #include <string.h>
  49. #include "rl_net.h"
  50. #define SOCKET_T int
  51. typedef int socklen_t ;
  52. static unsigned long inet_addr(const char *cp)
  53. {
  54. unsigned int a[4] ; unsigned long ret ;
  55. sscanf(cp, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3]) ;
  56. ret = ((a[3]<<24) + (a[2]<<16) + (a[1]<<8) + a[0]) ;
  57. return(ret) ;
  58. }
  59. #if defined(HAVE_KEIL_RTX)
  60. #define sleep(t) os_dly_wait(t/1000+1) ;
  61. #elif defined (WOLFSSL_CMSIS_RTOS)
  62. #define sleep(t) osDelay(t/1000+1) ;
  63. #endif
  64. #elif defined(WOLFSSL_TIRTOS)
  65. #include <string.h>
  66. #include <netdb.h>
  67. #include <sys/types.h>
  68. #include <arpa/inet.h>
  69. #include <sys/socket.h>
  70. #include <ti/sysbios/knl/Task.h>
  71. struct hostent {
  72. char *h_name; /* official name of host */
  73. char **h_aliases; /* alias list */
  74. int h_addrtype; /* host address type */
  75. int h_length; /* length of address */
  76. char **h_addr_list; /* list of addresses from name server */
  77. };
  78. #define SOCKET_T int
  79. #elif defined(WOLFSSL_VXWORKS)
  80. #include <hostLib.h>
  81. #include <sockLib.h>
  82. #include <arpa/inet.h>
  83. #include <string.h>
  84. #include <selectLib.h>
  85. #include <sys/types.h>
  86. #include <netinet/in.h>
  87. #include <fcntl.h>
  88. #include <sys/time.h>
  89. #include <netdb.h>
  90. #include <pthread.h>
  91. #define SOCKET_T int
  92. #else
  93. #include <string.h>
  94. #include <sys/types.h>
  95. #ifndef WOLFSSL_LEANPSK
  96. #include <unistd.h>
  97. #include <netdb.h>
  98. #include <netinet/in.h>
  99. #include <netinet/tcp.h>
  100. #include <arpa/inet.h>
  101. #include <sys/ioctl.h>
  102. #include <sys/time.h>
  103. #include <sys/socket.h>
  104. #include <pthread.h>
  105. #include <fcntl.h>
  106. #ifdef TEST_IPV6
  107. #include <netdb.h>
  108. #endif
  109. #endif
  110. #define SOCKET_T int
  111. #ifndef SO_NOSIGPIPE
  112. #include <signal.h> /* ignore SIGPIPE */
  113. #endif
  114. #define SNPRINTF snprintf
  115. #endif /* USE_WINDOWS_API */
  116. #ifdef WOLFSSL_ASYNC_CRYPT
  117. #include <wolfssl/wolfcrypt/async.h>
  118. #endif
  119. #ifdef HAVE_CAVIUM
  120. #include <wolfssl/wolfcrypt/port/cavium/cavium_nitrox.h>
  121. #endif
  122. #ifdef _MSC_VER
  123. /* disable conversion warning */
  124. /* 4996 warning to use MS extensions e.g., strcpy_s instead of strncpy */
  125. #pragma warning(disable:4244 4996)
  126. #endif
  127. /* Buffer for benchmark tests */
  128. #ifndef TEST_BUFFER_SIZE
  129. #define TEST_BUFFER_SIZE 16384
  130. #endif
  131. #ifndef WOLFSSL_HAVE_MIN
  132. #define WOLFSSL_HAVE_MIN
  133. static INLINE word32 min(word32 a, word32 b)
  134. {
  135. return a > b ? b : a;
  136. }
  137. #endif /* WOLFSSL_HAVE_MIN */
  138. /* Socket Handling */
  139. #ifndef WOLFSSL_SOCKET_INVALID
  140. #ifdef USE_WINDOWS_API
  141. #define WOLFSSL_SOCKET_INVALID ((SOCKET_T)INVALID_SOCKET)
  142. #elif defined(WOLFSSL_TIRTOS)
  143. #define WOLFSSL_SOCKET_INVALID ((SOCKET_T)-1)
  144. #else
  145. #define WOLFSSL_SOCKET_INVALID (SOCKET_T)(0)
  146. #endif
  147. #endif /* WOLFSSL_SOCKET_INVALID */
  148. #ifndef WOLFSSL_SOCKET_IS_INVALID
  149. #if defined(USE_WINDOWS_API) || defined(WOLFSSL_TIRTOS)
  150. #define WOLFSSL_SOCKET_IS_INVALID(s) ((SOCKET_T)(s) == WOLFSSL_SOCKET_INVALID)
  151. #else
  152. #define WOLFSSL_SOCKET_IS_INVALID(s) ((SOCKET_T)(s) < WOLFSSL_SOCKET_INVALID)
  153. #endif
  154. #endif /* WOLFSSL_SOCKET_IS_INVALID */
  155. #if defined(__MACH__) || defined(USE_WINDOWS_API)
  156. #ifndef _SOCKLEN_T
  157. typedef int socklen_t;
  158. #endif
  159. #endif
  160. /* HPUX doesn't use socklent_t for third parameter to accept, unless
  161. _XOPEN_SOURCE_EXTENDED is defined */
  162. #if !defined(__hpux__) && !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_IAR_ARM)\
  163. && !defined(WOLFSSL_ROWLEY_ARM) && !defined(WOLFSSL_KEIL_TCP_NET)
  164. typedef socklen_t* ACCEPT_THIRD_T;
  165. #else
  166. #if defined _XOPEN_SOURCE_EXTENDED
  167. typedef socklen_t* ACCEPT_THIRD_T;
  168. #else
  169. typedef int* ACCEPT_THIRD_T;
  170. #endif
  171. #endif
  172. #ifdef USE_WINDOWS_API
  173. #define CloseSocket(s) closesocket(s)
  174. #define StartTCP() { WSADATA wsd; WSAStartup(0x0002, &wsd); }
  175. #elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
  176. #define CloseSocket(s) closesocket(s)
  177. #define StartTCP()
  178. #else
  179. #define CloseSocket(s) close(s)
  180. #define StartTCP()
  181. #endif
  182. #ifdef SINGLE_THREADED
  183. typedef unsigned int THREAD_RETURN;
  184. typedef void* THREAD_TYPE;
  185. #define WOLFSSL_THREAD
  186. #else
  187. #if defined(_POSIX_THREADS) && !defined(__MINGW32__)
  188. typedef void* THREAD_RETURN;
  189. typedef pthread_t THREAD_TYPE;
  190. #define WOLFSSL_THREAD
  191. #define INFINITE -1
  192. #define WAIT_OBJECT_0 0L
  193. #elif defined(WOLFSSL_MDK_ARM)|| defined(WOLFSSL_KEIL_TCP_NET)
  194. typedef unsigned int THREAD_RETURN;
  195. typedef int THREAD_TYPE;
  196. #define WOLFSSL_THREAD
  197. #elif defined(WOLFSSL_TIRTOS)
  198. typedef void THREAD_RETURN;
  199. typedef Task_Handle THREAD_TYPE;
  200. #define WOLFSSL_THREAD
  201. #else
  202. typedef unsigned int THREAD_RETURN;
  203. typedef intptr_t THREAD_TYPE;
  204. #define WOLFSSL_THREAD __stdcall
  205. #endif
  206. #endif
  207. #ifdef TEST_IPV6
  208. typedef struct sockaddr_in6 SOCKADDR_IN_T;
  209. #define AF_INET_V AF_INET6
  210. #else
  211. typedef struct sockaddr_in SOCKADDR_IN_T;
  212. #define AF_INET_V AF_INET
  213. #endif
  214. #define SERVER_DEFAULT_VERSION 3
  215. #define SERVER_DTLS_DEFAULT_VERSION (-2)
  216. #define SERVER_INVALID_VERSION (-99)
  217. #define CLIENT_DEFAULT_VERSION 3
  218. #define CLIENT_DTLS_DEFAULT_VERSION (-2)
  219. #define CLIENT_INVALID_VERSION (-99)
  220. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_MAX_STRENGTH)
  221. #define DEFAULT_MIN_DHKEY_BITS 2048
  222. #else
  223. #define DEFAULT_MIN_DHKEY_BITS 1024
  224. #endif
  225. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_MAX_STRENGTH)
  226. #define DEFAULT_MIN_RSAKEY_BITS 2048
  227. #else
  228. #define DEFAULT_MIN_RSAKEY_BITS 1024
  229. #endif
  230. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_MAX_STRENGTH)
  231. #define DEFAULT_MIN_ECCKEY_BITS 256
  232. #else
  233. #define DEFAULT_MIN_ECCKEY_BITS 224
  234. #endif
  235. /* all certs relative to wolfSSL home directory now */
  236. #if defined(WOLFSSL_NO_CURRDIR) || defined(WOLFSSL_MDK_SHELL)
  237. #define caCertFile "certs/ca-cert.pem"
  238. #define eccCertFile "certs/server-ecc.pem"
  239. #define eccKeyFile "certs/ecc-key.pem"
  240. #define svrCertFile "certs/server-cert.pem"
  241. #define svrKeyFile "certs/server-key.pem"
  242. #define cliCertFile "certs/client-cert.pem"
  243. #define cliCertDerFile "certs/client-cert.der"
  244. #define cliKeyFile "certs/client-key.pem"
  245. #define ntruCertFile "certs/ntru-cert.pem"
  246. #define ntruKeyFile "certs/ntru-key.raw"
  247. #define dhParamFile "certs/dh2048.pem"
  248. #define cliEccKeyFile "certs/ecc-client-key.pem"
  249. #define cliEccCertFile "certs/client-ecc-cert.pem"
  250. #define caEccCertFile "certs/ca-ecc-cert/pem"
  251. #define crlPemDir "certs/crl"
  252. #ifdef HAVE_WNR
  253. /* Whitewood netRandom default config file */
  254. #define wnrConfig "wnr-example.conf"
  255. #endif
  256. #else
  257. #define caCertFile "./certs/ca-cert.pem"
  258. #define eccCertFile "./certs/server-ecc.pem"
  259. #define eccKeyFile "./certs/ecc-key.pem"
  260. #define svrCertFile "./certs/server-cert.pem"
  261. #define svrKeyFile "./certs/server-key.pem"
  262. #define cliCertFile "./certs/client-cert.pem"
  263. #define cliCertDerFile "./certs/client-cert.der"
  264. #define cliKeyFile "./certs/client-key.pem"
  265. #define ntruCertFile "./certs/ntru-cert.pem"
  266. #define ntruKeyFile "./certs/ntru-key.raw"
  267. #define dhParamFile "./certs/dh2048.pem"
  268. #define cliEccKeyFile "./certs/ecc-client-key.pem"
  269. #define cliEccCertFile "./certs/client-ecc-cert.pem"
  270. #define caEccCertFile "./certs/ca-ecc-cert.pem"
  271. #define crlPemDir "./certs/crl"
  272. #ifdef HAVE_WNR
  273. /* Whitewood netRandom default config file */
  274. #define wnrConfig "./wnr-example.conf"
  275. #endif
  276. #endif
  277. typedef struct tcp_ready {
  278. word16 ready; /* predicate */
  279. word16 port;
  280. char* srfName; /* server ready file name */
  281. #if defined(_POSIX_THREADS) && !defined(__MINGW32__)
  282. pthread_mutex_t mutex;
  283. pthread_cond_t cond;
  284. #endif
  285. } tcp_ready;
  286. static INLINE void InitTcpReady(tcp_ready* ready)
  287. {
  288. ready->ready = 0;
  289. ready->port = 0;
  290. ready->srfName = NULL;
  291. #ifdef SINGLE_THREADED
  292. #elif defined(_POSIX_THREADS) && !defined(__MINGW32__)
  293. pthread_mutex_init(&ready->mutex, 0);
  294. pthread_cond_init(&ready->cond, 0);
  295. #endif
  296. }
  297. static INLINE void FreeTcpReady(tcp_ready* ready)
  298. {
  299. #ifdef SINGLE_THREADED
  300. (void)ready;
  301. #elif defined(_POSIX_THREADS) && !defined(__MINGW32__)
  302. pthread_mutex_destroy(&ready->mutex);
  303. pthread_cond_destroy(&ready->cond);
  304. #else
  305. (void)ready;
  306. #endif
  307. }
  308. typedef WOLFSSL_METHOD* (*method_provider)(void);
  309. typedef void (*ctx_callback)(WOLFSSL_CTX* ctx);
  310. typedef void (*ssl_callback)(WOLFSSL* ssl);
  311. typedef struct callback_functions {
  312. method_provider method;
  313. ctx_callback ctx_ready;
  314. ssl_callback ssl_ready;
  315. ssl_callback on_result;
  316. } callback_functions;
  317. typedef struct func_args {
  318. int argc;
  319. char** argv;
  320. int return_code;
  321. tcp_ready* signal;
  322. callback_functions *callbacks;
  323. } func_args;
  324. void wait_tcp_ready(func_args*);
  325. typedef THREAD_RETURN WOLFSSL_THREAD THREAD_FUNC(void*);
  326. void start_thread(THREAD_FUNC, func_args*, THREAD_TYPE*);
  327. void join_thread(THREAD_TYPE);
  328. /* wolfSSL */
  329. #ifndef TEST_IPV6
  330. static const char* const wolfSSLIP = "127.0.0.1";
  331. #else
  332. static const char* const wolfSSLIP = "::1";
  333. #endif
  334. static const word16 wolfSSLPort = 11111;
  335. #if defined(__GNUC__)
  336. #define WC_NORETURN __attribute__((noreturn))
  337. #else
  338. #define WC_NORETURN
  339. #endif
  340. static INLINE WC_NORETURN void err_sys(const char* msg)
  341. {
  342. printf("wolfSSL error: %s\n", msg);
  343. #if !defined(__GNUC__)
  344. /* scan-build (which pretends to be gnuc) can get confused and think the
  345. * msg pointer can be null even when hardcoded and then it won't exit,
  346. * making null pointer checks above the err_sys() call useless.
  347. * We could just always exit() but some compilers will complain about no
  348. * possible return, with gcc we know the attribute to handle that with
  349. * WC_NORETURN. */
  350. if (msg)
  351. #endif
  352. {
  353. exit(EXIT_FAILURE);
  354. }
  355. }
  356. #define MY_EX_USAGE 2
  357. extern int myoptind;
  358. extern char* myoptarg;
  359. static INLINE int mygetopt(int argc, char** argv, const char* optstring)
  360. {
  361. static char* next = NULL;
  362. char c;
  363. char* cp;
  364. if (myoptind == 0)
  365. next = NULL; /* we're starting new/over */
  366. if (next == NULL || *next == '\0') {
  367. if (myoptind == 0)
  368. myoptind++;
  369. if (myoptind >= argc || argv[myoptind][0] != '-' ||
  370. argv[myoptind][1] == '\0') {
  371. myoptarg = NULL;
  372. if (myoptind < argc)
  373. myoptarg = argv[myoptind];
  374. return -1;
  375. }
  376. if (strcmp(argv[myoptind], "--") == 0) {
  377. myoptind++;
  378. myoptarg = NULL;
  379. if (myoptind < argc)
  380. myoptarg = argv[myoptind];
  381. return -1;
  382. }
  383. next = argv[myoptind];
  384. next++; /* skip - */
  385. myoptind++;
  386. }
  387. c = *next++;
  388. /* The C++ strchr can return a different value */
  389. cp = (char*)strchr(optstring, c);
  390. if (cp == NULL || c == ':')
  391. return '?';
  392. cp++;
  393. if (*cp == ':') {
  394. if (*next != '\0') {
  395. myoptarg = next;
  396. next = NULL;
  397. }
  398. else if (myoptind < argc) {
  399. myoptarg = argv[myoptind];
  400. myoptind++;
  401. }
  402. else
  403. return '?';
  404. }
  405. return c;
  406. }
  407. #if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
  408. static INLINE int PasswordCallBack(char* passwd, int sz, int rw, void* userdata)
  409. {
  410. (void)rw;
  411. (void)userdata;
  412. if (userdata != NULL) {
  413. strncpy(passwd, (char*)userdata, sz);
  414. return (int)XSTRLEN((char*)userdata);
  415. }
  416. else {
  417. strncpy(passwd, "yassl123", sz);
  418. return 8;
  419. }
  420. }
  421. #endif
  422. #if defined(KEEP_PEER_CERT) || defined(SESSION_CERTS)
  423. static INLINE void ShowX509(WOLFSSL_X509* x509, const char* hdr)
  424. {
  425. char* altName;
  426. char* issuer;
  427. char* subject;
  428. byte serial[32];
  429. int ret;
  430. int sz = sizeof(serial);
  431. if (x509 == NULL) {
  432. printf("%s No Cert\n", hdr);
  433. return;
  434. }
  435. issuer = wolfSSL_X509_NAME_oneline(
  436. wolfSSL_X509_get_issuer_name(x509), 0, 0);
  437. subject = wolfSSL_X509_NAME_oneline(
  438. wolfSSL_X509_get_subject_name(x509), 0, 0);
  439. printf("%s\n issuer : %s\n subject: %s\n", hdr, issuer, subject);
  440. while ( (altName = wolfSSL_X509_get_next_altname(x509)) != NULL)
  441. printf(" altname = %s\n", altName);
  442. ret = wolfSSL_X509_get_serial_number(x509, serial, &sz);
  443. if (ret == WOLFSSL_SUCCESS) {
  444. int i;
  445. int strLen;
  446. char serialMsg[80];
  447. /* testsuite has multiple threads writing to stdout, get output
  448. message ready to write once */
  449. strLen = sprintf(serialMsg, " serial number");
  450. for (i = 0; i < sz; i++)
  451. sprintf(serialMsg + strLen + (i*3), ":%02x ", serial[i]);
  452. printf("%s\n", serialMsg);
  453. }
  454. XFREE(subject, 0, DYNAMIC_TYPE_OPENSSL);
  455. XFREE(issuer, 0, DYNAMIC_TYPE_OPENSSL);
  456. #if defined(OPENSSL_EXTRA) && defined(SHOW_CERTS)
  457. {
  458. WOLFSSL_BIO* bio;
  459. char buf[256]; /* should be size of ASN_NAME_MAX */
  460. int textSz;
  461. /* print out domain component if certificate has it */
  462. textSz = wolfSSL_X509_NAME_get_text_by_NID(
  463. wolfSSL_X509_get_subject_name(x509), NID_domainComponent,
  464. buf, sizeof(buf));
  465. if (textSz > 0) {
  466. printf("Domain Component = %s\n", buf);
  467. }
  468. bio = wolfSSL_BIO_new(wolfSSL_BIO_s_file());
  469. if (bio != NULL) {
  470. wolfSSL_BIO_set_fp(bio, stdout, BIO_NOCLOSE);
  471. wolfSSL_X509_print(bio, x509);
  472. wolfSSL_BIO_free(bio);
  473. }
  474. }
  475. #endif
  476. }
  477. #endif /* KEEP_PEER_CERT || SESSION_CERTS */
  478. #if defined(SESSION_CERTS) && defined(SHOW_CERTS)
  479. static INLINE void ShowX509Chain(WOLFSSL_X509_CHAIN* chain, int count,
  480. const char* hdr)
  481. {
  482. int i;
  483. int length;
  484. unsigned char buffer[3072];
  485. WOLFSSL_X509* chainX509;
  486. for (i = 0; i < count; i++) {
  487. wolfSSL_get_chain_cert_pem(chain, i, buffer, sizeof(buffer), &length);
  488. buffer[length] = 0;
  489. printf("\n%s: %d has length %d data = \n%s\n", hdr, i, length, buffer);
  490. chainX509 = wolfSSL_get_chain_X509(chain, i);
  491. if (chainX509)
  492. ShowX509(chainX509, hdr);
  493. else
  494. printf("get_chain_X509 failed\n");
  495. wolfSSL_FreeX509(chainX509);
  496. }
  497. }
  498. #endif
  499. static INLINE void showPeer(WOLFSSL* ssl)
  500. {
  501. WOLFSSL_CIPHER* cipher;
  502. #ifdef HAVE_ECC
  503. const char *name;
  504. #endif
  505. #ifndef NO_DH
  506. int bits;
  507. #endif
  508. #ifdef KEEP_PEER_CERT
  509. WOLFSSL_X509* peer = wolfSSL_get_peer_certificate(ssl);
  510. if (peer)
  511. ShowX509(peer, "peer's cert info:");
  512. else
  513. printf("peer has no cert!\n");
  514. wolfSSL_FreeX509(peer);
  515. #endif
  516. #if defined(SHOW_CERTS) && defined(OPENSSL_EXTRA) && defined(KEEP_OUR_CERT)
  517. ShowX509(wolfSSL_get_certificate(ssl), "our cert info:");
  518. printf("Peer verify result = %lu\n", wolfSSL_get_verify_result(ssl));
  519. #endif /* SHOW_CERTS */
  520. printf("SSL version is %s\n", wolfSSL_get_version(ssl));
  521. cipher = wolfSSL_get_current_cipher(ssl);
  522. #ifdef HAVE_QSH
  523. printf("SSL cipher suite is %s%s\n", (wolfSSL_isQSH(ssl))? "QSH:": "",
  524. wolfSSL_CIPHER_get_name(cipher));
  525. #else
  526. printf("SSL cipher suite is %s\n", wolfSSL_CIPHER_get_name(cipher));
  527. #endif
  528. #ifdef HAVE_ECC
  529. if ((name = wolfSSL_get_curve_name(ssl)) != NULL)
  530. printf("SSL curve name is %s\n", name);
  531. #endif
  532. #ifndef NO_DH
  533. if ((bits = wolfSSL_GetDhKey_Sz(ssl)) > 0)
  534. printf("SSL DH size is %d bits\n", bits);
  535. #endif
  536. if (wolfSSL_session_reused(ssl))
  537. printf("SSL reused session\n");
  538. #ifdef WOLFSSL_ALT_CERT_CHAINS
  539. if (wolfSSL_is_peer_alt_cert_chain(ssl))
  540. printf("Alternate cert chain used\n");
  541. #endif
  542. #if defined(SESSION_CERTS) && defined(SHOW_CERTS)
  543. {
  544. WOLFSSL_X509_CHAIN* chain;
  545. chain = wolfSSL_get_peer_chain(ssl);
  546. ShowX509Chain(chain, wolfSSL_get_chain_count(chain), "session cert");
  547. #ifdef WOLFSSL_ALT_CERT_CHAINS
  548. if (wolfSSL_is_peer_alt_cert_chain(ssl)) {
  549. chain = wolfSSL_get_peer_alt_chain(ssl);
  550. ShowX509Chain(chain, wolfSSL_get_chain_count(chain), "alt cert");
  551. }
  552. #endif
  553. }
  554. #endif /* SESSION_CERTS && SHOW_CERTS */
  555. (void)ssl;
  556. }
  557. static INLINE void build_addr(SOCKADDR_IN_T* addr, const char* peer,
  558. word16 port, int udp, int sctp)
  559. {
  560. int useLookup = 0;
  561. (void)useLookup;
  562. (void)udp;
  563. (void)sctp;
  564. if (addr == NULL)
  565. err_sys("invalid argument to build_addr, addr is NULL");
  566. memset(addr, 0, sizeof(SOCKADDR_IN_T));
  567. #ifndef TEST_IPV6
  568. /* peer could be in human readable form */
  569. if ( ((size_t)peer != INADDR_ANY) && isalpha((int)peer[0])) {
  570. #if defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
  571. int err;
  572. struct hostent* entry = gethostbyname(peer, &err);
  573. #elif defined(WOLFSSL_TIRTOS)
  574. struct hostent* entry = DNSGetHostByName(peer);
  575. #elif defined(WOLFSSL_VXWORKS)
  576. struct hostent* entry = (struct hostent*)hostGetByName((char*)peer);
  577. #else
  578. struct hostent* entry = gethostbyname(peer);
  579. #endif
  580. if (entry) {
  581. XMEMCPY(&addr->sin_addr.s_addr, entry->h_addr_list[0],
  582. entry->h_length);
  583. useLookup = 1;
  584. }
  585. else
  586. err_sys("no entry for host");
  587. }
  588. #endif
  589. #ifndef TEST_IPV6
  590. #if defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
  591. addr->sin_family = PF_INET;
  592. #else
  593. addr->sin_family = AF_INET_V;
  594. #endif
  595. addr->sin_port = XHTONS(port);
  596. if ((size_t)peer == INADDR_ANY)
  597. addr->sin_addr.s_addr = INADDR_ANY;
  598. else {
  599. if (!useLookup)
  600. addr->sin_addr.s_addr = inet_addr(peer);
  601. }
  602. #else
  603. addr->sin6_family = AF_INET_V;
  604. addr->sin6_port = XHTONS(port);
  605. if (peer == INADDR_ANY)
  606. addr->sin6_addr = in6addr_any;
  607. else {
  608. #ifdef HAVE_GETADDRINFO
  609. struct addrinfo hints;
  610. struct addrinfo* answer = NULL;
  611. int ret;
  612. char strPort[80];
  613. memset(&hints, 0, sizeof(hints));
  614. hints.ai_family = AF_INET_V;
  615. if (udp) {
  616. hints.ai_socktype = SOCK_DGRAM;
  617. hints.ai_protocol = IPPROTO_UDP;
  618. }
  619. #ifdef WOLFSSL_SCTP
  620. else if (sctp) {
  621. hints.ai_socktype = SOCK_STREAM;
  622. hints.ai_protocol = IPPROTO_SCTP;
  623. }
  624. #endif
  625. else {
  626. hints.ai_socktype = SOCK_STREAM;
  627. hints.ai_protocol = IPPROTO_TCP;
  628. }
  629. SNPRINTF(strPort, sizeof(strPort), "%d", port);
  630. strPort[79] = '\0';
  631. ret = getaddrinfo(peer, strPort, &hints, &answer);
  632. if (ret < 0 || answer == NULL)
  633. err_sys("getaddrinfo failed");
  634. XMEMCPY(addr, answer->ai_addr, answer->ai_addrlen);
  635. freeaddrinfo(answer);
  636. #else
  637. printf("no ipv6 getaddrinfo, loopback only tests/examples\n");
  638. addr->sin6_addr = in6addr_loopback;
  639. #endif
  640. }
  641. #endif
  642. }
  643. static INLINE void tcp_socket(SOCKET_T* sockfd, int udp, int sctp)
  644. {
  645. (void)sctp;
  646. if (udp)
  647. *sockfd = socket(AF_INET_V, SOCK_DGRAM, IPPROTO_UDP);
  648. #ifdef WOLFSSL_SCTP
  649. else if (sctp)
  650. *sockfd = socket(AF_INET_V, SOCK_STREAM, IPPROTO_SCTP);
  651. #endif
  652. else
  653. *sockfd = socket(AF_INET_V, SOCK_STREAM, IPPROTO_TCP);
  654. if(WOLFSSL_SOCKET_IS_INVALID(*sockfd)) {
  655. err_sys("socket failed\n");
  656. }
  657. #ifndef USE_WINDOWS_API
  658. #ifdef SO_NOSIGPIPE
  659. {
  660. int on = 1;
  661. socklen_t len = sizeof(on);
  662. int res = setsockopt(*sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, len);
  663. if (res < 0)
  664. err_sys("setsockopt SO_NOSIGPIPE failed\n");
  665. }
  666. #elif defined(WOLFSSL_MDK_ARM) || defined (WOLFSSL_TIRTOS) ||\
  667. defined(WOLFSSL_KEIL_TCP_NET)
  668. /* nothing to define */
  669. #else /* no S_NOSIGPIPE */
  670. signal(SIGPIPE, SIG_IGN);
  671. #endif /* S_NOSIGPIPE */
  672. #if defined(TCP_NODELAY)
  673. if (!udp && !sctp)
  674. {
  675. int on = 1;
  676. socklen_t len = sizeof(on);
  677. int res = setsockopt(*sockfd, IPPROTO_TCP, TCP_NODELAY, &on, len);
  678. if (res < 0)
  679. err_sys("setsockopt TCP_NODELAY failed\n");
  680. }
  681. #endif
  682. #endif /* USE_WINDOWS_API */
  683. }
  684. static INLINE void tcp_connect(SOCKET_T* sockfd, const char* ip, word16 port,
  685. int udp, int sctp, WOLFSSL* ssl)
  686. {
  687. SOCKADDR_IN_T addr;
  688. build_addr(&addr, ip, port, udp, sctp);
  689. if (udp) {
  690. wolfSSL_dtls_set_peer(ssl, &addr, sizeof(addr));
  691. }
  692. tcp_socket(sockfd, udp, sctp);
  693. if (!udp) {
  694. if (connect(*sockfd, (const struct sockaddr*)&addr, sizeof(addr)) != 0)
  695. err_sys("tcp connect failed");
  696. }
  697. }
  698. static INLINE void udp_connect(SOCKET_T* sockfd, void* addr, int addrSz)
  699. {
  700. if (connect(*sockfd, (const struct sockaddr*)addr, addrSz) != 0)
  701. err_sys("tcp connect failed");
  702. }
  703. enum {
  704. TEST_SELECT_FAIL,
  705. TEST_TIMEOUT,
  706. TEST_RECV_READY,
  707. TEST_ERROR_READY
  708. };
  709. #if !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_KEIL_TCP_NET) && \
  710. !defined(WOLFSSL_TIRTOS)
  711. static INLINE int tcp_select(SOCKET_T socketfd, int to_sec)
  712. {
  713. fd_set recvfds, errfds;
  714. SOCKET_T nfds = socketfd + 1;
  715. #if !defined(__INTEGRITY)
  716. struct timeval timeout = {(to_sec > 0) ? to_sec : 0, 0};
  717. #else
  718. struct timeval timeout;
  719. #endif
  720. int result;
  721. FD_ZERO(&recvfds);
  722. FD_SET(socketfd, &recvfds);
  723. FD_ZERO(&errfds);
  724. FD_SET(socketfd, &errfds);
  725. #if defined(__INTEGRITY)
  726. timeout.tv_sec = (long long)(to_sec > 0) ? to_sec : 0, 0;
  727. #endif
  728. result = select(nfds, &recvfds, NULL, &errfds, &timeout);
  729. if (result == 0)
  730. return TEST_TIMEOUT;
  731. else if (result > 0) {
  732. if (FD_ISSET(socketfd, &recvfds))
  733. return TEST_RECV_READY;
  734. else if(FD_ISSET(socketfd, &errfds))
  735. return TEST_ERROR_READY;
  736. }
  737. return TEST_SELECT_FAIL;
  738. }
  739. #elif defined(WOLFSSL_TIRTOS) || defined(WOLFSSL_KEIL_TCP_NET)
  740. static INLINE int tcp_select(SOCKET_T socketfd, int to_sec)
  741. {
  742. return TEST_RECV_READY;
  743. }
  744. #endif /* !WOLFSSL_MDK_ARM */
  745. static INLINE void tcp_listen(SOCKET_T* sockfd, word16* port, int useAnyAddr,
  746. int udp, int sctp)
  747. {
  748. SOCKADDR_IN_T addr;
  749. /* don't use INADDR_ANY by default, firewall may block, make user switch
  750. on */
  751. build_addr(&addr, (useAnyAddr ? INADDR_ANY : wolfSSLIP), *port, udp, sctp);
  752. tcp_socket(sockfd, udp, sctp);
  753. #if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_MDK_ARM)\
  754. && !defined(WOLFSSL_KEIL_TCP_NET)
  755. {
  756. int res, on = 1;
  757. socklen_t len = sizeof(on);
  758. res = setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &on, len);
  759. if (res < 0)
  760. err_sys("setsockopt SO_REUSEADDR failed\n");
  761. }
  762. #endif
  763. if (bind(*sockfd, (const struct sockaddr*)&addr, sizeof(addr)) != 0)
  764. err_sys("tcp bind failed");
  765. if (!udp) {
  766. #ifdef WOLFSSL_KEIL_TCP_NET
  767. #define SOCK_LISTEN_MAX_QUEUE 1
  768. #else
  769. #define SOCK_LISTEN_MAX_QUEUE 5
  770. #endif
  771. if (listen(*sockfd, SOCK_LISTEN_MAX_QUEUE) != 0)
  772. err_sys("tcp listen failed");
  773. }
  774. #if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_TIRTOS)
  775. if (*port == 0) {
  776. socklen_t len = sizeof(addr);
  777. if (getsockname(*sockfd, (struct sockaddr*)&addr, &len) == 0) {
  778. #ifndef TEST_IPV6
  779. *port = XNTOHS(addr.sin_port);
  780. #else
  781. *port = XNTOHS(addr.sin6_port);
  782. #endif
  783. }
  784. }
  785. #endif
  786. }
  787. #if 0
  788. static INLINE int udp_read_connect(SOCKET_T sockfd)
  789. {
  790. SOCKADDR_IN_T cliaddr;
  791. byte b[1500];
  792. int n;
  793. socklen_t len = sizeof(cliaddr);
  794. n = (int)recvfrom(sockfd, (char*)b, sizeof(b), MSG_PEEK,
  795. (struct sockaddr*)&cliaddr, &len);
  796. if (n > 0) {
  797. if (connect(sockfd, (const struct sockaddr*)&cliaddr,
  798. sizeof(cliaddr)) != 0)
  799. err_sys("udp connect failed");
  800. }
  801. else
  802. err_sys("recvfrom failed");
  803. return sockfd;
  804. }
  805. #endif
  806. static INLINE void udp_accept(SOCKET_T* sockfd, SOCKET_T* clientfd,
  807. int useAnyAddr, word16 port, func_args* args)
  808. {
  809. SOCKADDR_IN_T addr;
  810. (void)args;
  811. build_addr(&addr, (useAnyAddr ? INADDR_ANY : wolfSSLIP), port, 1, 0);
  812. tcp_socket(sockfd, 1, 0);
  813. #if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_MDK_ARM) \
  814. && !defined(WOLFSSL_KEIL_TCP_NET)
  815. {
  816. int res, on = 1;
  817. socklen_t len = sizeof(on);
  818. res = setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &on, len);
  819. if (res < 0)
  820. err_sys("setsockopt SO_REUSEADDR failed\n");
  821. }
  822. #endif
  823. if (bind(*sockfd, (const struct sockaddr*)&addr, sizeof(addr)) != 0)
  824. err_sys("tcp bind failed");
  825. #if (defined(NO_MAIN_DRIVER) && !defined(USE_WINDOWS_API)) && !defined(WOLFSSL_TIRTOS)
  826. if (port == 0) {
  827. socklen_t len = sizeof(addr);
  828. if (getsockname(*sockfd, (struct sockaddr*)&addr, &len) == 0) {
  829. #ifndef TEST_IPV6
  830. port = XNTOHS(addr.sin_port);
  831. #else
  832. port = XNTOHS(addr.sin6_port);
  833. #endif
  834. }
  835. }
  836. #endif
  837. #if defined(_POSIX_THREADS) && defined(NO_MAIN_DRIVER) && !defined(__MINGW32__)
  838. /* signal ready to accept data */
  839. {
  840. tcp_ready* ready = args->signal;
  841. pthread_mutex_lock(&ready->mutex);
  842. ready->ready = 1;
  843. ready->port = port;
  844. pthread_cond_signal(&ready->cond);
  845. pthread_mutex_unlock(&ready->mutex);
  846. }
  847. #elif defined (WOLFSSL_TIRTOS)
  848. /* Need mutex? */
  849. tcp_ready* ready = args->signal;
  850. ready->ready = 1;
  851. ready->port = port;
  852. #endif
  853. *clientfd = *sockfd;
  854. }
  855. static INLINE void tcp_accept(SOCKET_T* sockfd, SOCKET_T* clientfd,
  856. func_args* args, word16 port, int useAnyAddr,
  857. int udp, int sctp, int ready_file, int do_listen)
  858. {
  859. SOCKADDR_IN_T client;
  860. socklen_t client_len = sizeof(client);
  861. tcp_ready* ready = NULL;
  862. (void) ready; /* Account for case when "ready" is not used */
  863. if (udp) {
  864. udp_accept(sockfd, clientfd, useAnyAddr, port, args);
  865. return;
  866. }
  867. if(do_listen) {
  868. tcp_listen(sockfd, &port, useAnyAddr, udp, sctp);
  869. #if defined(_POSIX_THREADS) && defined(NO_MAIN_DRIVER) && !defined(__MINGW32__)
  870. /* signal ready to tcp_accept */
  871. if (args)
  872. ready = args->signal;
  873. if (ready) {
  874. pthread_mutex_lock(&ready->mutex);
  875. ready->ready = 1;
  876. ready->port = port;
  877. pthread_cond_signal(&ready->cond);
  878. pthread_mutex_unlock(&ready->mutex);
  879. }
  880. #elif defined (WOLFSSL_TIRTOS)
  881. /* Need mutex? */
  882. if (args)
  883. ready = args->signal;
  884. if (ready) {
  885. ready->ready = 1;
  886. ready->port = port;
  887. }
  888. #endif
  889. if (ready_file) {
  890. #if !defined(NO_FILESYSTEM) || defined(FORCE_BUFFER_TEST)
  891. FILE* srf = NULL;
  892. if (args)
  893. ready = args->signal;
  894. if (ready) {
  895. srf = fopen(ready->srfName, "w");
  896. if (srf) {
  897. /* let's write port sever is listening on to ready file
  898. external monitor can then do ephemeral ports by passing
  899. -p 0 to server on supported platforms with -R ready_file
  900. client can then wait for existence of ready_file and see
  901. which port the server is listening on. */
  902. fprintf(srf, "%d\n", (int)port);
  903. fclose(srf);
  904. }
  905. }
  906. #endif
  907. }
  908. }
  909. *clientfd = accept(*sockfd, (struct sockaddr*)&client,
  910. (ACCEPT_THIRD_T)&client_len);
  911. if(WOLFSSL_SOCKET_IS_INVALID(*clientfd)) {
  912. err_sys("tcp accept failed");
  913. }
  914. }
  915. static INLINE void tcp_set_nonblocking(SOCKET_T* sockfd)
  916. {
  917. #ifdef USE_WINDOWS_API
  918. unsigned long blocking = 1;
  919. int ret = ioctlsocket(*sockfd, FIONBIO, &blocking);
  920. if (ret == SOCKET_ERROR)
  921. err_sys("ioctlsocket failed");
  922. #elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET) \
  923. || defined (WOLFSSL_TIRTOS)|| defined(WOLFSSL_VXWORKS)
  924. /* non blocking not supported, for now */
  925. #else
  926. int flags = fcntl(*sockfd, F_GETFL, 0);
  927. if (flags < 0)
  928. err_sys("fcntl get failed");
  929. flags = fcntl(*sockfd, F_SETFL, flags | O_NONBLOCK);
  930. if (flags < 0)
  931. err_sys("fcntl set failed");
  932. #endif
  933. }
  934. #ifndef NO_PSK
  935. /* identity is OpenSSL testing default for openssl s_client, keep same */
  936. static const char* kIdentityStr = "Client_identity";
  937. static INLINE unsigned int my_psk_client_cb(WOLFSSL* ssl, const char* hint,
  938. char* identity, unsigned int id_max_len, unsigned char* key,
  939. unsigned int key_max_len)
  940. {
  941. (void)ssl;
  942. (void)hint;
  943. (void)key_max_len;
  944. /* see internal.h MAX_PSK_ID_LEN for PSK identity limit */
  945. strncpy(identity, kIdentityStr, id_max_len);
  946. /* test key in hex is 0x1a2b3c4d , in decimal 439,041,101 , we're using
  947. unsigned binary */
  948. key[0] = 26;
  949. key[1] = 43;
  950. key[2] = 60;
  951. key[3] = 77;
  952. return 4; /* length of key in octets or 0 for error */
  953. }
  954. static INLINE unsigned int my_psk_server_cb(WOLFSSL* ssl, const char* identity,
  955. unsigned char* key, unsigned int key_max_len)
  956. {
  957. (void)ssl;
  958. (void)key_max_len;
  959. /* see internal.h MAX_PSK_ID_LEN for PSK identity limit */
  960. if (strncmp(identity, kIdentityStr, strlen(kIdentityStr)) != 0)
  961. return 0;
  962. /* test key in hex is 0x1a2b3c4d , in decimal 439,041,101 , we're using
  963. unsigned binary */
  964. key[0] = 26;
  965. key[1] = 43;
  966. key[2] = 60;
  967. key[3] = 77;
  968. return 4; /* length of key in octets or 0 for error */
  969. }
  970. #endif /* NO_PSK */
  971. #if defined(WOLFSSL_USER_CURRTIME)
  972. extern double current_time(int reset);
  973. #elif defined(USE_WINDOWS_API)
  974. #define WIN32_LEAN_AND_MEAN
  975. #include <windows.h>
  976. static INLINE double current_time(int reset)
  977. {
  978. static int init = 0;
  979. static LARGE_INTEGER freq;
  980. LARGE_INTEGER count;
  981. if (!init) {
  982. QueryPerformanceFrequency(&freq);
  983. init = 1;
  984. }
  985. QueryPerformanceCounter(&count);
  986. (void)reset;
  987. return (double)count.QuadPart / freq.QuadPart;
  988. }
  989. #elif defined(WOLFSSL_TIRTOS)
  990. extern double current_time();
  991. #else
  992. #if !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_KEIL_TCP_NET) && !defined(WOLFSSL_CHIBIOS)
  993. #include <sys/time.h>
  994. static INLINE double current_time(int reset)
  995. {
  996. struct timeval tv;
  997. gettimeofday(&tv, 0);
  998. (void)reset;
  999. return (double)tv.tv_sec + (double)tv.tv_usec / 1000000;
  1000. }
  1001. #else
  1002. extern double current_time(int reset);
  1003. #endif
  1004. #endif /* USE_WINDOWS_API */
  1005. #if defined(HAVE_OCSP) && defined(WOLFSSL_NONBLOCK_OCSP)
  1006. static INLINE int OCSPIOCb(void* ioCtx, const char* url, int urlSz,
  1007. unsigned char* request, int requestSz, unsigned char** response)
  1008. {
  1009. #ifdef TEST_NONBLOCK_CERTS
  1010. static int ioCbCnt = 0;
  1011. #endif
  1012. (void)ioCtx;
  1013. (void)url;
  1014. (void)urlSz;
  1015. (void)request;
  1016. (void)requestSz;
  1017. (void)response;
  1018. #ifdef TEST_NONBLOCK_CERTS
  1019. if (ioCbCnt) {
  1020. ioCbCnt = 0;
  1021. return EmbedOcspLookup(ioCtx, url, urlSz, request, requestSz, response);
  1022. }
  1023. else {
  1024. ioCbCnt = 1;
  1025. return WOLFSSL_CBIO_ERR_WANT_READ;
  1026. }
  1027. #else
  1028. return EmbedOcspLookup(ioCtx, url, urlSz, request, requestSz, response);
  1029. #endif
  1030. }
  1031. static INLINE void OCSPRespFreeCb(void* ioCtx, unsigned char* response)
  1032. {
  1033. (void)ioCtx;
  1034. (void)response;
  1035. }
  1036. #endif
  1037. #if !defined(NO_CERTS)
  1038. #if !defined(NO_FILESYSTEM) || \
  1039. (defined(NO_FILESYSTEM) && defined(FORCE_BUFFER_TEST))
  1040. /* reads file size, allocates buffer, reads into buffer, returns buffer */
  1041. static INLINE int load_file(const char* fname, byte** buf, size_t* bufLen)
  1042. {
  1043. int ret;
  1044. long int fileSz;
  1045. FILE* file;
  1046. if (fname == NULL || buf == NULL || bufLen == NULL)
  1047. return BAD_FUNC_ARG;
  1048. /* set defaults */
  1049. *buf = NULL;
  1050. *bufLen = 0;
  1051. /* open file (read-only binary) */
  1052. file = fopen(fname, "rb");
  1053. if (!file) {
  1054. printf("Error loading %s\n", fname);
  1055. return BAD_PATH_ERROR;
  1056. }
  1057. fseek(file, 0, SEEK_END);
  1058. fileSz = (int)ftell(file);
  1059. rewind(file);
  1060. if (fileSz > 0) {
  1061. *bufLen = (size_t)fileSz;
  1062. *buf = (byte*)malloc(*bufLen);
  1063. if (*buf == NULL) {
  1064. ret = MEMORY_E;
  1065. printf("Error allocating %lu bytes\n", (unsigned long)*bufLen);
  1066. }
  1067. else {
  1068. size_t readLen = fread(*buf, *bufLen, 1, file);
  1069. /* check response code */
  1070. ret = (readLen > 0) ? 0 : -1;
  1071. }
  1072. }
  1073. else {
  1074. ret = BUFFER_E;
  1075. }
  1076. fclose(file);
  1077. return ret;
  1078. }
  1079. enum {
  1080. WOLFSSL_CA = 1,
  1081. WOLFSSL_CERT = 2,
  1082. WOLFSSL_KEY = 3,
  1083. WOLFSSL_CERT_CHAIN = 4,
  1084. };
  1085. static INLINE void load_buffer(WOLFSSL_CTX* ctx, const char* fname, int type)
  1086. {
  1087. int format = WOLFSSL_FILETYPE_PEM;
  1088. byte* buff = NULL;
  1089. size_t sz = 0;
  1090. if (load_file(fname, &buff, &sz) != 0) {
  1091. err_sys("can't open file for buffer load "
  1092. "Please run from wolfSSL home directory if not");
  1093. }
  1094. /* determine format */
  1095. if (strstr(fname, ".der"))
  1096. format = WOLFSSL_FILETYPE_ASN1;
  1097. if (type == WOLFSSL_CA) {
  1098. if (wolfSSL_CTX_load_verify_buffer(ctx, buff, (long)sz, format)
  1099. != WOLFSSL_SUCCESS)
  1100. err_sys("can't load buffer ca file");
  1101. }
  1102. else if (type == WOLFSSL_CERT) {
  1103. if (wolfSSL_CTX_use_certificate_buffer(ctx, buff, (long)sz,
  1104. format) != WOLFSSL_SUCCESS)
  1105. err_sys("can't load buffer cert file");
  1106. }
  1107. else if (type == WOLFSSL_KEY) {
  1108. if (wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, (long)sz,
  1109. format) != WOLFSSL_SUCCESS)
  1110. err_sys("can't load buffer key file");
  1111. }
  1112. else if (type == WOLFSSL_CERT_CHAIN) {
  1113. if (wolfSSL_CTX_use_certificate_chain_buffer_format(ctx, buff,
  1114. (long)sz, format) != WOLFSSL_SUCCESS)
  1115. err_sys("can't load cert chain buffer");
  1116. }
  1117. if (buff)
  1118. free(buff);
  1119. }
  1120. #endif /* !NO_FILESYSTEM || (NO_FILESYSTEM && FORCE_BUFFER_TEST) */
  1121. #endif /* !NO_CERTS */
  1122. static INLINE int myVerify(int preverify, WOLFSSL_X509_STORE_CTX* store)
  1123. {
  1124. char buffer[WOLFSSL_MAX_ERROR_SZ];
  1125. #ifdef OPENSSL_EXTRA
  1126. WOLFSSL_X509* peer;
  1127. #endif
  1128. (void)preverify;
  1129. printf("In verification callback, error = %d, %s\n", store->error,
  1130. wolfSSL_ERR_error_string(store->error, buffer));
  1131. #ifdef OPENSSL_EXTRA
  1132. peer = store->current_cert;
  1133. if (peer) {
  1134. char* issuer = wolfSSL_X509_NAME_oneline(
  1135. wolfSSL_X509_get_issuer_name(peer), 0, 0);
  1136. char* subject = wolfSSL_X509_NAME_oneline(
  1137. wolfSSL_X509_get_subject_name(peer), 0, 0);
  1138. printf("\tPeer's cert info:\n issuer : %s\n subject: %s\n", issuer,
  1139. subject);
  1140. XFREE(subject, 0, DYNAMIC_TYPE_OPENSSL);
  1141. XFREE(issuer, 0, DYNAMIC_TYPE_OPENSSL);
  1142. }
  1143. else
  1144. printf("\tPeer has no cert!\n");
  1145. #else
  1146. printf("\tPeer certs: %d\n", store->totalCerts);
  1147. #ifdef SHOW_CERTS
  1148. { int i;
  1149. for (i=0; i<store->totalCerts; i++) {
  1150. WOLFSSL_BUFFER_INFO* cert = &store->certs[i];
  1151. printf("\t\tCert %d: Ptr %p, Len %u\n", i, cert->buffer, cert->length);
  1152. }
  1153. }
  1154. #endif
  1155. #endif
  1156. printf("\tSubject's domain name is %s\n", store->domain);
  1157. printf("\tAllowing to continue anyway (shouldn't do this, EVER!!!)\n");
  1158. return 1;
  1159. }
  1160. static INLINE int myDateCb(int preverify, WOLFSSL_X509_STORE_CTX* store)
  1161. {
  1162. char buffer[WOLFSSL_MAX_ERROR_SZ];
  1163. (void)preverify;
  1164. printf("In verification callback, error = %d, %s\n", store->error,
  1165. wolfSSL_ERR_error_string(store->error, buffer));
  1166. printf("Subject's domain name is %s\n", store->domain);
  1167. if (store->error == ASN_BEFORE_DATE_E || store->error == ASN_AFTER_DATE_E) {
  1168. printf("Overriding cert date error as example for bad clock testing\n");
  1169. return 1;
  1170. }
  1171. printf("Cert error is not date error, not overriding\n");
  1172. return 0;
  1173. }
  1174. #ifdef HAVE_CRL
  1175. static INLINE void CRL_CallBack(const char* url)
  1176. {
  1177. printf("CRL callback url = %s\n", url);
  1178. }
  1179. #endif
  1180. #ifndef NO_DH
  1181. static INLINE void SetDH(WOLFSSL* ssl)
  1182. {
  1183. /* dh1024 p */
  1184. static unsigned char p[] =
  1185. {
  1186. 0xE6, 0x96, 0x9D, 0x3D, 0x49, 0x5B, 0xE3, 0x2C, 0x7C, 0xF1, 0x80, 0xC3,
  1187. 0xBD, 0xD4, 0x79, 0x8E, 0x91, 0xB7, 0x81, 0x82, 0x51, 0xBB, 0x05, 0x5E,
  1188. 0x2A, 0x20, 0x64, 0x90, 0x4A, 0x79, 0xA7, 0x70, 0xFA, 0x15, 0xA2, 0x59,
  1189. 0xCB, 0xD5, 0x23, 0xA6, 0xA6, 0xEF, 0x09, 0xC4, 0x30, 0x48, 0xD5, 0xA2,
  1190. 0x2F, 0x97, 0x1F, 0x3C, 0x20, 0x12, 0x9B, 0x48, 0x00, 0x0E, 0x6E, 0xDD,
  1191. 0x06, 0x1C, 0xBC, 0x05, 0x3E, 0x37, 0x1D, 0x79, 0x4E, 0x53, 0x27, 0xDF,
  1192. 0x61, 0x1E, 0xBB, 0xBE, 0x1B, 0xAC, 0x9B, 0x5C, 0x60, 0x44, 0xCF, 0x02,
  1193. 0x3D, 0x76, 0xE0, 0x5E, 0xEA, 0x9B, 0xAD, 0x99, 0x1B, 0x13, 0xA6, 0x3C,
  1194. 0x97, 0x4E, 0x9E, 0xF1, 0x83, 0x9E, 0xB5, 0xDB, 0x12, 0x51, 0x36, 0xF7,
  1195. 0x26, 0x2E, 0x56, 0xA8, 0x87, 0x15, 0x38, 0xDF, 0xD8, 0x23, 0xC6, 0x50,
  1196. 0x50, 0x85, 0xE2, 0x1F, 0x0D, 0xD5, 0xC8, 0x6B,
  1197. };
  1198. /* dh1024 g */
  1199. static unsigned char g[] =
  1200. {
  1201. 0x02,
  1202. };
  1203. wolfSSL_SetTmpDH(ssl, p, sizeof(p), g, sizeof(g));
  1204. }
  1205. static INLINE void SetDHCtx(WOLFSSL_CTX* ctx)
  1206. {
  1207. /* dh1024 p */
  1208. static unsigned char p[] =
  1209. {
  1210. 0xE6, 0x96, 0x9D, 0x3D, 0x49, 0x5B, 0xE3, 0x2C, 0x7C, 0xF1, 0x80, 0xC3,
  1211. 0xBD, 0xD4, 0x79, 0x8E, 0x91, 0xB7, 0x81, 0x82, 0x51, 0xBB, 0x05, 0x5E,
  1212. 0x2A, 0x20, 0x64, 0x90, 0x4A, 0x79, 0xA7, 0x70, 0xFA, 0x15, 0xA2, 0x59,
  1213. 0xCB, 0xD5, 0x23, 0xA6, 0xA6, 0xEF, 0x09, 0xC4, 0x30, 0x48, 0xD5, 0xA2,
  1214. 0x2F, 0x97, 0x1F, 0x3C, 0x20, 0x12, 0x9B, 0x48, 0x00, 0x0E, 0x6E, 0xDD,
  1215. 0x06, 0x1C, 0xBC, 0x05, 0x3E, 0x37, 0x1D, 0x79, 0x4E, 0x53, 0x27, 0xDF,
  1216. 0x61, 0x1E, 0xBB, 0xBE, 0x1B, 0xAC, 0x9B, 0x5C, 0x60, 0x44, 0xCF, 0x02,
  1217. 0x3D, 0x76, 0xE0, 0x5E, 0xEA, 0x9B, 0xAD, 0x99, 0x1B, 0x13, 0xA6, 0x3C,
  1218. 0x97, 0x4E, 0x9E, 0xF1, 0x83, 0x9E, 0xB5, 0xDB, 0x12, 0x51, 0x36, 0xF7,
  1219. 0x26, 0x2E, 0x56, 0xA8, 0x87, 0x15, 0x38, 0xDF, 0xD8, 0x23, 0xC6, 0x50,
  1220. 0x50, 0x85, 0xE2, 0x1F, 0x0D, 0xD5, 0xC8, 0x6B,
  1221. };
  1222. /* dh1024 g */
  1223. static unsigned char g[] =
  1224. {
  1225. 0x02,
  1226. };
  1227. wolfSSL_CTX_SetTmpDH(ctx, p, sizeof(p), g, sizeof(g));
  1228. }
  1229. #endif /* NO_DH */
  1230. #ifndef NO_CERTS
  1231. static INLINE void CaCb(unsigned char* der, int sz, int type)
  1232. {
  1233. (void)der;
  1234. printf("Got CA cache add callback, derSz = %d, type = %d\n", sz, type);
  1235. }
  1236. #endif /* !NO_CERTS */
  1237. /* Wolf Root Directory Helper */
  1238. /* KEIL-RL File System does not support relative directory */
  1239. #if !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_KEIL_FS) && !defined(WOLFSSL_TIRTOS)
  1240. /* Maximum depth to search for WolfSSL root */
  1241. #define MAX_WOLF_ROOT_DEPTH 5
  1242. static INLINE int ChangeToWolfRoot(void)
  1243. {
  1244. #if !defined(NO_FILESYSTEM) || defined(FORCE_BUFFER_TEST)
  1245. int depth, res;
  1246. FILE* file;
  1247. for(depth = 0; depth <= MAX_WOLF_ROOT_DEPTH; depth++) {
  1248. file = fopen(ntruKeyFile, "rb");
  1249. if (file != NULL) {
  1250. fclose(file);
  1251. return depth;
  1252. }
  1253. #ifdef USE_WINDOWS_API
  1254. res = SetCurrentDirectoryA("..\\");
  1255. #else
  1256. res = chdir("../");
  1257. #endif
  1258. if (res < 0) {
  1259. printf("chdir to ../ failed!\n");
  1260. break;
  1261. }
  1262. }
  1263. err_sys("wolf root not found");
  1264. return -1;
  1265. #else
  1266. return 0;
  1267. #endif
  1268. }
  1269. #endif /* !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_KEIL_FS) && !defined(WOLFSSL_TIRTOS) */
  1270. #ifdef HAVE_STACK_SIZE
  1271. typedef THREAD_RETURN WOLFSSL_THREAD (*thread_func)(void* args);
  1272. #define STACK_CHECK_VAL 0x01
  1273. static INLINE int StackSizeCheck(func_args* args, thread_func tf)
  1274. {
  1275. int ret, i, used;
  1276. void* status;
  1277. unsigned char* myStack = NULL;
  1278. int stackSize = 1024*128;
  1279. pthread_attr_t myAttr;
  1280. pthread_t threadId;
  1281. #ifdef PTHREAD_STACK_MIN
  1282. if (stackSize < PTHREAD_STACK_MIN)
  1283. stackSize = PTHREAD_STACK_MIN;
  1284. #endif
  1285. ret = posix_memalign((void**)&myStack, sysconf(_SC_PAGESIZE), stackSize);
  1286. if (ret != 0 || myStack == NULL)
  1287. err_sys("posix_memalign failed\n");
  1288. XMEMSET(myStack, STACK_CHECK_VAL, stackSize);
  1289. ret = pthread_attr_init(&myAttr);
  1290. if (ret != 0)
  1291. err_sys("attr_init failed");
  1292. ret = pthread_attr_setstack(&myAttr, myStack, stackSize);
  1293. if (ret != 0)
  1294. err_sys("attr_setstackaddr failed");
  1295. ret = pthread_create(&threadId, &myAttr, tf, args);
  1296. if (ret != 0) {
  1297. perror("pthread_create failed");
  1298. exit(EXIT_FAILURE);
  1299. }
  1300. ret = pthread_join(threadId, &status);
  1301. if (ret != 0)
  1302. err_sys("pthread_join failed");
  1303. for (i = 0; i < stackSize; i++) {
  1304. if (myStack[i] != STACK_CHECK_VAL) {
  1305. break;
  1306. }
  1307. }
  1308. free(myStack);
  1309. used = stackSize - i;
  1310. printf("stack used = %d\n", used);
  1311. return (int)((size_t)status);
  1312. }
  1313. #endif /* HAVE_STACK_SIZE */
  1314. #ifdef STACK_TRAP
  1315. /* good settings
  1316. --enable-debug --disable-shared C_EXTRA_FLAGS="-DUSER_TIME -DTFM_TIMING_RESISTANT -DPOSITIVE_EXP_ONLY -DSTACK_TRAP"
  1317. */
  1318. #ifdef HAVE_STACK_SIZE
  1319. /* client only for now, setrlimit will fail if pthread_create() called */
  1320. /* STACK_SIZE does pthread_create() on client */
  1321. #error "can't use STACK_TRAP with STACK_SIZE, setrlimit will fail"
  1322. #endif /* HAVE_STACK_SIZE */
  1323. static INLINE void StackTrap(void)
  1324. {
  1325. struct rlimit rl;
  1326. if (getrlimit(RLIMIT_STACK, &rl) != 0)
  1327. err_sys("getrlimit failed");
  1328. printf("rlim_cur = %llu\n", rl.rlim_cur);
  1329. rl.rlim_cur = 1024*21; /* adjust trap size here */
  1330. if (setrlimit(RLIMIT_STACK, &rl) != 0) {
  1331. perror("setrlimit");
  1332. err_sys("setrlimit failed");
  1333. }
  1334. }
  1335. #else /* STACK_TRAP */
  1336. static INLINE void StackTrap(void)
  1337. {
  1338. }
  1339. #endif /* STACK_TRAP */
  1340. #ifdef ATOMIC_USER
  1341. /* Atomic Encrypt Context example */
  1342. typedef struct AtomicEncCtx {
  1343. int keySetup; /* have we done key setup yet */
  1344. Aes aes; /* for aes example */
  1345. } AtomicEncCtx;
  1346. /* Atomic Decrypt Context example */
  1347. typedef struct AtomicDecCtx {
  1348. int keySetup; /* have we done key setup yet */
  1349. Aes aes; /* for aes example */
  1350. } AtomicDecCtx;
  1351. static INLINE int myMacEncryptCb(WOLFSSL* ssl, unsigned char* macOut,
  1352. const unsigned char* macIn, unsigned int macInSz, int macContent,
  1353. int macVerify, unsigned char* encOut, const unsigned char* encIn,
  1354. unsigned int encSz, void* ctx)
  1355. {
  1356. int ret;
  1357. Hmac hmac;
  1358. byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
  1359. AtomicEncCtx* encCtx = (AtomicEncCtx*)ctx;
  1360. const char* tlsStr = "TLS";
  1361. /* example supports (d)tls aes */
  1362. if (wolfSSL_GetBulkCipher(ssl) != wolfssl_aes) {
  1363. printf("myMacEncryptCb not using AES\n");
  1364. return -1;
  1365. }
  1366. if (strstr(wolfSSL_get_version(ssl), tlsStr) == NULL) {
  1367. printf("myMacEncryptCb not using (D)TLS\n");
  1368. return -1;
  1369. }
  1370. /* hmac, not needed if aead mode */
  1371. wolfSSL_SetTlsHmacInner(ssl, myInner, macInSz, macContent, macVerify);
  1372. ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
  1373. wolfSSL_GetMacSecret(ssl, macVerify), wolfSSL_GetHmacSize(ssl));
  1374. if (ret != 0)
  1375. return ret;
  1376. ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
  1377. if (ret != 0)
  1378. return ret;
  1379. ret = wc_HmacUpdate(&hmac, macIn, macInSz);
  1380. if (ret != 0)
  1381. return ret;
  1382. ret = wc_HmacFinal(&hmac, macOut);
  1383. if (ret != 0)
  1384. return ret;
  1385. /* encrypt setup on first time */
  1386. if (encCtx->keySetup == 0) {
  1387. int keyLen = wolfSSL_GetKeySize(ssl);
  1388. const byte* key;
  1389. const byte* iv;
  1390. if (wolfSSL_GetSide(ssl) == WOLFSSL_CLIENT_END) {
  1391. key = wolfSSL_GetClientWriteKey(ssl);
  1392. iv = wolfSSL_GetClientWriteIV(ssl);
  1393. }
  1394. else {
  1395. key = wolfSSL_GetServerWriteKey(ssl);
  1396. iv = wolfSSL_GetServerWriteIV(ssl);
  1397. }
  1398. ret = wc_AesSetKey(&encCtx->aes, key, keyLen, iv, AES_ENCRYPTION);
  1399. if (ret != 0) {
  1400. printf("AesSetKey failed in myMacEncryptCb\n");
  1401. return ret;
  1402. }
  1403. encCtx->keySetup = 1;
  1404. }
  1405. /* encrypt */
  1406. return wc_AesCbcEncrypt(&encCtx->aes, encOut, encIn, encSz);
  1407. }
  1408. static INLINE int myDecryptVerifyCb(WOLFSSL* ssl,
  1409. unsigned char* decOut, const unsigned char* decIn,
  1410. unsigned int decSz, int macContent, int macVerify,
  1411. unsigned int* padSz, void* ctx)
  1412. {
  1413. AtomicDecCtx* decCtx = (AtomicDecCtx*)ctx;
  1414. int ret = 0;
  1415. int macInSz = 0;
  1416. int ivExtra = 0;
  1417. int digestSz = wolfSSL_GetHmacSize(ssl);
  1418. unsigned int pad = 0;
  1419. unsigned int padByte = 0;
  1420. Hmac hmac;
  1421. byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
  1422. byte verify[WC_MAX_DIGEST_SIZE];
  1423. const char* tlsStr = "TLS";
  1424. /* example supports (d)tls aes */
  1425. if (wolfSSL_GetBulkCipher(ssl) != wolfssl_aes) {
  1426. printf("myMacEncryptCb not using AES\n");
  1427. return -1;
  1428. }
  1429. if (strstr(wolfSSL_get_version(ssl), tlsStr) == NULL) {
  1430. printf("myMacEncryptCb not using (D)TLS\n");
  1431. return -1;
  1432. }
  1433. /*decrypt */
  1434. if (decCtx->keySetup == 0) {
  1435. int keyLen = wolfSSL_GetKeySize(ssl);
  1436. const byte* key;
  1437. const byte* iv;
  1438. /* decrypt is from other side (peer) */
  1439. if (wolfSSL_GetSide(ssl) == WOLFSSL_SERVER_END) {
  1440. key = wolfSSL_GetClientWriteKey(ssl);
  1441. iv = wolfSSL_GetClientWriteIV(ssl);
  1442. }
  1443. else {
  1444. key = wolfSSL_GetServerWriteKey(ssl);
  1445. iv = wolfSSL_GetServerWriteIV(ssl);
  1446. }
  1447. ret = wc_AesSetKey(&decCtx->aes, key, keyLen, iv, AES_DECRYPTION);
  1448. if (ret != 0) {
  1449. printf("AesSetKey failed in myDecryptVerifyCb\n");
  1450. return ret;
  1451. }
  1452. decCtx->keySetup = 1;
  1453. }
  1454. /* decrypt */
  1455. ret = wc_AesCbcDecrypt(&decCtx->aes, decOut, decIn, decSz);
  1456. if (ret != 0)
  1457. return ret;
  1458. if (wolfSSL_GetCipherType(ssl) == WOLFSSL_AEAD_TYPE) {
  1459. *padSz = wolfSSL_GetAeadMacSize(ssl);
  1460. return 0; /* hmac, not needed if aead mode */
  1461. }
  1462. if (wolfSSL_GetCipherType(ssl) == WOLFSSL_BLOCK_TYPE) {
  1463. pad = *(decOut + decSz - 1);
  1464. padByte = 1;
  1465. if (wolfSSL_IsTLSv1_1(ssl))
  1466. ivExtra = wolfSSL_GetCipherBlockSize(ssl);
  1467. }
  1468. *padSz = wolfSSL_GetHmacSize(ssl) + pad + padByte;
  1469. macInSz = decSz - ivExtra - digestSz - pad - padByte;
  1470. wolfSSL_SetTlsHmacInner(ssl, myInner, macInSz, macContent, macVerify);
  1471. ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
  1472. wolfSSL_GetMacSecret(ssl, macVerify), digestSz);
  1473. if (ret != 0)
  1474. return ret;
  1475. ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
  1476. if (ret != 0)
  1477. return ret;
  1478. ret = wc_HmacUpdate(&hmac, decOut + ivExtra, macInSz);
  1479. if (ret != 0)
  1480. return ret;
  1481. ret = wc_HmacFinal(&hmac, verify);
  1482. if (ret != 0)
  1483. return ret;
  1484. if (XMEMCMP(verify, decOut + decSz - digestSz - pad - padByte,
  1485. digestSz) != 0) {
  1486. printf("myDecryptVerify verify failed\n");
  1487. return -1;
  1488. }
  1489. return ret;
  1490. }
  1491. static INLINE void SetupAtomicUser(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
  1492. {
  1493. AtomicEncCtx* encCtx;
  1494. AtomicDecCtx* decCtx;
  1495. encCtx = (AtomicEncCtx*)malloc(sizeof(AtomicEncCtx));
  1496. if (encCtx == NULL)
  1497. err_sys("AtomicEncCtx malloc failed");
  1498. memset(encCtx, 0, sizeof(AtomicEncCtx));
  1499. decCtx = (AtomicDecCtx*)malloc(sizeof(AtomicDecCtx));
  1500. if (decCtx == NULL) {
  1501. free(encCtx);
  1502. err_sys("AtomicDecCtx malloc failed");
  1503. }
  1504. memset(decCtx, 0, sizeof(AtomicDecCtx));
  1505. wolfSSL_CTX_SetMacEncryptCb(ctx, myMacEncryptCb);
  1506. wolfSSL_SetMacEncryptCtx(ssl, encCtx);
  1507. wolfSSL_CTX_SetDecryptVerifyCb(ctx, myDecryptVerifyCb);
  1508. wolfSSL_SetDecryptVerifyCtx(ssl, decCtx);
  1509. }
  1510. static INLINE void FreeAtomicUser(WOLFSSL* ssl)
  1511. {
  1512. AtomicEncCtx* encCtx = (AtomicEncCtx*)wolfSSL_GetMacEncryptCtx(ssl);
  1513. AtomicDecCtx* decCtx = (AtomicDecCtx*)wolfSSL_GetDecryptVerifyCtx(ssl);
  1514. free(decCtx);
  1515. free(encCtx);
  1516. }
  1517. #endif /* ATOMIC_USER */
  1518. #ifdef WOLFSSL_STATIC_MEMORY
  1519. static INLINE int wolfSSL_PrintStats(WOLFSSL_MEM_STATS* stats)
  1520. {
  1521. word16 i;
  1522. if (stats == NULL) {
  1523. return 0;
  1524. }
  1525. /* print to stderr so is on the same pipe as WOLFSSL_DEBUG */
  1526. fprintf(stderr, "Total mallocs = %d\n", stats->totalAlloc);
  1527. fprintf(stderr, "Total frees = %d\n", stats->totalFr);
  1528. fprintf(stderr, "Current mallocs = %d\n", stats->curAlloc);
  1529. fprintf(stderr, "Available IO = %d\n", stats->avaIO);
  1530. fprintf(stderr, "Max con. handshakes = %d\n", stats->maxHa);
  1531. fprintf(stderr, "Max con. IO = %d\n", stats->maxIO);
  1532. fprintf(stderr, "State of memory blocks: size : available \n");
  1533. for (i = 0; i < WOLFMEM_MAX_BUCKETS; i++) {
  1534. fprintf(stderr, " : %d\t : %d\n", stats->blockSz[i],
  1535. stats->avaBlock[i]);
  1536. }
  1537. return 1;
  1538. }
  1539. #endif /* WOLFSSL_STATIC_MEMORY */
  1540. #ifdef HAVE_PK_CALLBACKS
  1541. #ifdef HAVE_ECC
  1542. static INLINE int myEccSign(WOLFSSL* ssl, const byte* in, word32 inSz,
  1543. byte* out, word32* outSz, const byte* key, word32 keySz, void* ctx)
  1544. {
  1545. WC_RNG rng;
  1546. int ret;
  1547. word32 idx = 0;
  1548. ecc_key myKey;
  1549. (void)ssl;
  1550. (void)ctx;
  1551. ret = wc_InitRng(&rng);
  1552. if (ret != 0)
  1553. return ret;
  1554. ret = wc_ecc_init(&myKey);
  1555. if (ret == 0) {
  1556. ret = wc_EccPrivateKeyDecode(key, &idx, &myKey, keySz);
  1557. if (ret == 0)
  1558. ret = wc_ecc_sign_hash(in, inSz, out, outSz, &rng, &myKey);
  1559. wc_ecc_free(&myKey);
  1560. }
  1561. wc_FreeRng(&rng);
  1562. return ret;
  1563. }
  1564. static INLINE int myEccVerify(WOLFSSL* ssl, const byte* sig, word32 sigSz,
  1565. const byte* hash, word32 hashSz, const byte* key, word32 keySz,
  1566. int* result, void* ctx)
  1567. {
  1568. int ret;
  1569. ecc_key myKey;
  1570. (void)ssl;
  1571. (void)ctx;
  1572. ret = wc_ecc_init(&myKey);
  1573. if (ret == 0) {
  1574. ret = wc_ecc_import_x963(key, keySz, &myKey);
  1575. if (ret == 0)
  1576. ret = wc_ecc_verify_hash(sig, sigSz, hash, hashSz, result, &myKey);
  1577. wc_ecc_free(&myKey);
  1578. }
  1579. return ret;
  1580. }
  1581. static INLINE int myEccSharedSecret(WOLFSSL* ssl, ecc_key* otherKey,
  1582. unsigned char* pubKeyDer, unsigned int* pubKeySz,
  1583. unsigned char* out, unsigned int* outlen,
  1584. int side, void* ctx)
  1585. {
  1586. int ret;
  1587. ecc_key* privKey = NULL;
  1588. ecc_key* pubKey = NULL;
  1589. ecc_key tmpKey;
  1590. (void)ssl;
  1591. (void)ctx;
  1592. ret = wc_ecc_init(&tmpKey);
  1593. if (ret != 0) {
  1594. return ret;
  1595. }
  1596. /* for client: create and export public key */
  1597. if (side == WOLFSSL_CLIENT_END) {
  1598. WC_RNG rng;
  1599. privKey = &tmpKey;
  1600. pubKey = otherKey;
  1601. ret = wc_InitRng(&rng);
  1602. if (ret == 0) {
  1603. ret = wc_ecc_make_key_ex(&rng, 0, privKey, otherKey->dp->id);
  1604. #ifdef WOLFSSL_ASYNC_CRYPT
  1605. if (ret == WC_PENDING_E) {
  1606. ret = wc_AsyncWait(ret, &privKey->asyncDev, WC_ASYNC_FLAG_NONE);
  1607. }
  1608. #endif
  1609. if (ret == 0)
  1610. ret = wc_ecc_export_x963(privKey, pubKeyDer, pubKeySz);
  1611. wc_FreeRng(&rng);
  1612. }
  1613. }
  1614. /* for server: import public key */
  1615. else if (side == WOLFSSL_SERVER_END) {
  1616. privKey = otherKey;
  1617. pubKey = &tmpKey;
  1618. ret = wc_ecc_import_x963_ex(pubKeyDer, *pubKeySz, pubKey,
  1619. otherKey->dp->id);
  1620. }
  1621. else {
  1622. ret = BAD_FUNC_ARG;
  1623. }
  1624. /* generate shared secret and return it */
  1625. if (ret == 0) {
  1626. ret = wc_ecc_shared_secret(privKey, pubKey, out, outlen);
  1627. #ifdef WOLFSSL_ASYNC_CRYPT
  1628. if (ret == WC_PENDING_E) {
  1629. ret = wc_AsyncWait(ret, &privKey->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  1630. }
  1631. #endif
  1632. }
  1633. wc_ecc_free(&tmpKey);
  1634. return ret;
  1635. }
  1636. #ifdef HAVE_ED25519
  1637. static INLINE int myEd25519Sign(WOLFSSL* ssl, const byte* in, word32 inSz,
  1638. byte* out, word32* outSz, const byte* key, word32 keySz, void* ctx)
  1639. {
  1640. int ret;
  1641. word32 idx = 0;
  1642. ed25519_key myKey;
  1643. (void)ssl;
  1644. (void)ctx;
  1645. ret = wc_ed25519_init(&myKey);
  1646. if (ret == 0) {
  1647. ret = wc_Ed25519PrivateKeyDecode(key, &idx, &myKey, keySz);
  1648. if (ret == 0)
  1649. ret = wc_ed25519_sign_msg(in, inSz, out, outSz, &myKey);
  1650. wc_ed25519_free(&myKey);
  1651. }
  1652. return ret;
  1653. }
  1654. static INLINE int myEd25519Verify(WOLFSSL* ssl, const byte* sig, word32 sigSz,
  1655. const byte* msg, word32 msgSz, const byte* key, word32 keySz,
  1656. int* result, void* ctx)
  1657. {
  1658. int ret;
  1659. ed25519_key myKey;
  1660. (void)ssl;
  1661. (void)ctx;
  1662. ret = wc_ed25519_init(&myKey);
  1663. if (ret == 0) {
  1664. ret = wc_ed25519_import_public(key, keySz, &myKey);
  1665. if (ret == 0) {
  1666. ret = wc_ed25519_verify_msg(sig, sigSz, msg, msgSz, result, &myKey);
  1667. }
  1668. wc_ed25519_free(&myKey);
  1669. }
  1670. return ret;
  1671. }
  1672. #endif /* HAVE_ED25519 */
  1673. #ifdef HAVE_CURVE25519
  1674. static INLINE int myX25519SharedSecret(WOLFSSL* ssl, curve25519_key* otherKey,
  1675. unsigned char* pubKeyDer, unsigned int* pubKeySz,
  1676. unsigned char* out, unsigned int* outlen,
  1677. int side, void* ctx)
  1678. {
  1679. int ret;
  1680. curve25519_key* privKey = NULL;
  1681. curve25519_key* pubKey = NULL;
  1682. curve25519_key tmpKey;
  1683. (void)ssl;
  1684. (void)ctx;
  1685. ret = wc_curve25519_init(&tmpKey);
  1686. if (ret != 0) {
  1687. return ret;
  1688. }
  1689. /* for client: create and export public key */
  1690. if (side == WOLFSSL_CLIENT_END) {
  1691. WC_RNG rng;
  1692. privKey = &tmpKey;
  1693. pubKey = otherKey;
  1694. ret = wc_InitRng(&rng);
  1695. if (ret == 0) {
  1696. ret = wc_curve25519_make_key(&rng, CURVE25519_KEYSIZE, privKey);
  1697. if (ret == 0) {
  1698. ret = wc_curve25519_export_public_ex(privKey, pubKeyDer,
  1699. pubKeySz, EC25519_LITTLE_ENDIAN);
  1700. }
  1701. wc_FreeRng(&rng);
  1702. }
  1703. }
  1704. /* for server: import public key */
  1705. else if (side == WOLFSSL_SERVER_END) {
  1706. privKey = otherKey;
  1707. pubKey = &tmpKey;
  1708. ret = wc_curve25519_import_public_ex(pubKeyDer, *pubKeySz, pubKey,
  1709. EC25519_LITTLE_ENDIAN);
  1710. }
  1711. else {
  1712. ret = BAD_FUNC_ARG;
  1713. }
  1714. /* generate shared secret and return it */
  1715. if (ret == 0) {
  1716. ret = wc_curve25519_shared_secret_ex(privKey, pubKey, out, outlen,
  1717. EC25519_LITTLE_ENDIAN);
  1718. }
  1719. wc_curve25519_free(&tmpKey);
  1720. return ret;
  1721. }
  1722. #endif /* HAVE_CURVE25519 */
  1723. #endif /* HAVE_ECC */
  1724. #ifndef NO_DH
  1725. static INLINE int myDhCallback(WOLFSSL* ssl, struct DhKey* key,
  1726. const unsigned char* priv, unsigned int privSz,
  1727. const unsigned char* pubKeyDer, unsigned int pubKeySz,
  1728. unsigned char* out, unsigned int* outlen,
  1729. void* ctx)
  1730. {
  1731. (void)ctx;
  1732. (void)ssl;
  1733. /* return 0 on success */
  1734. return wc_DhAgree(key, out, outlen, priv, privSz, pubKeyDer, pubKeySz);
  1735. };
  1736. #endif /* !NO_DH */
  1737. #ifndef NO_RSA
  1738. static INLINE int myRsaSign(WOLFSSL* ssl, const byte* in, word32 inSz,
  1739. byte* out, word32* outSz, const byte* key, word32 keySz, void* ctx)
  1740. {
  1741. WC_RNG rng;
  1742. int ret;
  1743. word32 idx = 0;
  1744. RsaKey myKey;
  1745. (void)ssl;
  1746. (void)ctx;
  1747. ret = wc_InitRng(&rng);
  1748. if (ret != 0)
  1749. return ret;
  1750. ret = wc_InitRsaKey(&myKey, NULL);
  1751. if (ret == 0) {
  1752. ret = wc_RsaPrivateKeyDecode(key, &idx, &myKey, keySz);
  1753. if (ret == 0)
  1754. ret = wc_RsaSSL_Sign(in, inSz, out, *outSz, &myKey, &rng);
  1755. if (ret > 0) { /* save and convert to 0 success */
  1756. *outSz = ret;
  1757. ret = 0;
  1758. }
  1759. wc_FreeRsaKey(&myKey);
  1760. }
  1761. wc_FreeRng(&rng);
  1762. return ret;
  1763. }
  1764. static INLINE int myRsaVerify(WOLFSSL* ssl, byte* sig, word32 sigSz,
  1765. byte** out,
  1766. const byte* key, word32 keySz,
  1767. void* ctx)
  1768. {
  1769. int ret;
  1770. word32 idx = 0;
  1771. RsaKey myKey;
  1772. (void)ssl;
  1773. (void)ctx;
  1774. ret = wc_InitRsaKey(&myKey, NULL);
  1775. if (ret == 0) {
  1776. ret = wc_RsaPublicKeyDecode(key, &idx, &myKey, keySz);
  1777. if (ret == 0)
  1778. ret = wc_RsaSSL_VerifyInline(sig, sigSz, out, &myKey);
  1779. wc_FreeRsaKey(&myKey);
  1780. }
  1781. return ret;
  1782. }
  1783. #ifdef WC_RSA_PSS
  1784. static INLINE int myRsaPssSign(WOLFSSL* ssl, const byte* in, word32 inSz,
  1785. byte* out, word32* outSz, int hash, int mgf, const byte* key,
  1786. word32 keySz, void* ctx)
  1787. {
  1788. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  1789. WC_RNG rng;
  1790. int ret;
  1791. word32 idx = 0;
  1792. RsaKey myKey;
  1793. (void)ssl;
  1794. (void)ctx;
  1795. switch (hash) {
  1796. #ifndef NO_SHA256
  1797. case SHA256h:
  1798. hashType = WC_HASH_TYPE_SHA256;
  1799. break;
  1800. #endif
  1801. #ifdef WOLFSSL_SHA384
  1802. case SHA384h:
  1803. hashType = WC_HASH_TYPE_SHA384;
  1804. break;
  1805. #endif
  1806. #ifdef WOLFSSL_SHA512
  1807. case SHA512h:
  1808. hashType = WC_HASH_TYPE_SHA512;
  1809. break;
  1810. #endif
  1811. }
  1812. ret = wc_InitRng(&rng);
  1813. if (ret != 0)
  1814. return ret;
  1815. ret = wc_InitRsaKey(&myKey, NULL);
  1816. if (ret == 0) {
  1817. ret = wc_RsaPrivateKeyDecode(key, &idx, &myKey, keySz);
  1818. if (ret == 0) {
  1819. ret = wc_RsaPSS_Sign(in, inSz, out, *outSz, hashType, mgf, &myKey,
  1820. &rng);
  1821. }
  1822. if (ret > 0) { /* save and convert to 0 success */
  1823. *outSz = ret;
  1824. ret = 0;
  1825. }
  1826. wc_FreeRsaKey(&myKey);
  1827. }
  1828. wc_FreeRng(&rng);
  1829. return ret;
  1830. }
  1831. static INLINE int myRsaPssVerify(WOLFSSL* ssl, byte* sig, word32 sigSz,
  1832. byte** out, int hash, int mgf, const byte* key, word32 keySz, void* ctx)
  1833. {
  1834. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  1835. int ret;
  1836. word32 idx = 0;
  1837. RsaKey myKey;
  1838. (void)ssl;
  1839. (void)ctx;
  1840. switch (hash) {
  1841. #ifndef NO_SHA256
  1842. case SHA256h:
  1843. hashType = WC_HASH_TYPE_SHA256;
  1844. break;
  1845. #endif
  1846. #ifdef WOLFSSL_SHA384
  1847. case SHA384h:
  1848. hashType = WC_HASH_TYPE_SHA384;
  1849. break;
  1850. #endif
  1851. #ifdef WOLFSSL_SHA512
  1852. case SHA512h:
  1853. hashType = WC_HASH_TYPE_SHA512;
  1854. break;
  1855. #endif
  1856. }
  1857. ret = wc_InitRsaKey(&myKey, NULL);
  1858. if (ret == 0) {
  1859. ret = wc_RsaPublicKeyDecode(key, &idx, &myKey, keySz);
  1860. if (ret == 0) {
  1861. ret = wc_RsaPSS_VerifyInline(sig, sigSz, out, hashType, mgf,
  1862. &myKey);
  1863. }
  1864. wc_FreeRsaKey(&myKey);
  1865. }
  1866. return ret;
  1867. }
  1868. #endif
  1869. static INLINE int myRsaEnc(WOLFSSL* ssl, const byte* in, word32 inSz,
  1870. byte* out, word32* outSz, const byte* key,
  1871. word32 keySz, void* ctx)
  1872. {
  1873. int ret;
  1874. word32 idx = 0;
  1875. RsaKey myKey;
  1876. WC_RNG rng;
  1877. (void)ssl;
  1878. (void)ctx;
  1879. ret = wc_InitRng(&rng);
  1880. if (ret != 0)
  1881. return ret;
  1882. ret = wc_InitRsaKey(&myKey, NULL);
  1883. if (ret == 0) {
  1884. ret = wc_RsaPublicKeyDecode(key, &idx, &myKey, keySz);
  1885. if (ret == 0) {
  1886. ret = wc_RsaPublicEncrypt(in, inSz, out, *outSz, &myKey, &rng);
  1887. if (ret > 0) {
  1888. *outSz = ret;
  1889. ret = 0; /* reset to success */
  1890. }
  1891. }
  1892. wc_FreeRsaKey(&myKey);
  1893. }
  1894. wc_FreeRng(&rng);
  1895. return ret;
  1896. }
  1897. static INLINE int myRsaDec(WOLFSSL* ssl, byte* in, word32 inSz,
  1898. byte** out,
  1899. const byte* key, word32 keySz, void* ctx)
  1900. {
  1901. int ret;
  1902. word32 idx = 0;
  1903. RsaKey myKey;
  1904. (void)ssl;
  1905. (void)ctx;
  1906. ret = wc_InitRsaKey(&myKey, NULL);
  1907. if (ret == 0) {
  1908. ret = wc_RsaPrivateKeyDecode(key, &idx, &myKey, keySz);
  1909. if (ret == 0) {
  1910. #ifdef WC_RSA_BLINDING
  1911. ret = wc_RsaSetRNG(&myKey, wolfSSL_GetRNG(ssl));
  1912. if (ret != 0) {
  1913. wc_FreeRsaKey(&myKey);
  1914. return ret;
  1915. }
  1916. #endif
  1917. ret = wc_RsaPrivateDecryptInline(in, inSz, out, &myKey);
  1918. }
  1919. wc_FreeRsaKey(&myKey);
  1920. }
  1921. return ret;
  1922. }
  1923. #endif /* NO_RSA */
  1924. static INLINE void SetupPkCallbacks(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
  1925. {
  1926. (void)ctx;
  1927. (void)ssl;
  1928. #ifdef HAVE_ECC
  1929. wolfSSL_CTX_SetEccSignCb(ctx, myEccSign);
  1930. wolfSSL_CTX_SetEccVerifyCb(ctx, myEccVerify);
  1931. wolfSSL_CTX_SetEccSharedSecretCb(ctx, myEccSharedSecret);
  1932. #endif /* HAVE_ECC */
  1933. #ifndef NO_DH
  1934. wolfSSL_CTX_SetDhAgreeCb(ctx, myDhCallback);
  1935. #endif
  1936. #ifdef HAVE_ED25519
  1937. wolfSSL_CTX_SetEd25519SignCb(ctx, myEd25519Sign);
  1938. wolfSSL_CTX_SetEd25519VerifyCb(ctx, myEd25519Verify);
  1939. #endif
  1940. #ifdef HAVE_CURVE25519
  1941. wolfSSL_CTX_SetX25519SharedSecretCb(ctx, myX25519SharedSecret);
  1942. #endif
  1943. #ifndef NO_RSA
  1944. wolfSSL_CTX_SetRsaSignCb(ctx, myRsaSign);
  1945. wolfSSL_CTX_SetRsaVerifyCb(ctx, myRsaVerify);
  1946. #ifdef WC_RSA_PSS
  1947. wolfSSL_CTX_SetRsaPssSignCb(ctx, myRsaPssSign);
  1948. wolfSSL_CTX_SetRsaPssVerifyCb(ctx, myRsaPssVerify);
  1949. #endif
  1950. wolfSSL_CTX_SetRsaEncCb(ctx, myRsaEnc);
  1951. wolfSSL_CTX_SetRsaDecCb(ctx, myRsaDec);
  1952. #endif /* NO_RSA */
  1953. }
  1954. #endif /* HAVE_PK_CALLBACKS */
  1955. #if defined(__hpux__) || defined(__MINGW32__) || defined (WOLFSSL_TIRTOS) \
  1956. || defined(_MSC_VER)
  1957. /* HP/UX doesn't have strsep, needed by test/suites.c */
  1958. static INLINE char* strsep(char **stringp, const char *delim)
  1959. {
  1960. char* start;
  1961. char* end;
  1962. start = *stringp;
  1963. if (start == NULL)
  1964. return NULL;
  1965. if ((end = strpbrk(start, delim))) {
  1966. *end++ = '\0';
  1967. *stringp = end;
  1968. } else {
  1969. *stringp = NULL;
  1970. }
  1971. return start;
  1972. }
  1973. #endif /* __hpux__ and others */
  1974. /* Create unique filename, len is length of tempfn name, assuming
  1975. len does not include null terminating character,
  1976. num is number of characters in tempfn name to randomize */
  1977. static INLINE const char* mymktemp(char *tempfn, int len, int num)
  1978. {
  1979. int x, size;
  1980. static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1981. "abcdefghijklmnopqrstuvwxyz";
  1982. WC_RNG rng;
  1983. byte out;
  1984. if (tempfn == NULL || len < 1 || num < 1 || len <= num) {
  1985. printf("Bad input\n");
  1986. return NULL;
  1987. }
  1988. size = len - 1;
  1989. if (wc_InitRng(&rng) != 0) {
  1990. printf("InitRng failed\n");
  1991. return NULL;
  1992. }
  1993. for (x = size; x > size - num; x--) {
  1994. if (wc_RNG_GenerateBlock(&rng,(byte*)&out, sizeof(out)) != 0) {
  1995. printf("RNG_GenerateBlock failed\n");
  1996. return NULL;
  1997. }
  1998. tempfn[x] = alphanum[out % (sizeof(alphanum) - 1)];
  1999. }
  2000. tempfn[len] = '\0';
  2001. wc_FreeRng(&rng);
  2002. return tempfn;
  2003. }
  2004. #if defined(HAVE_SESSION_TICKET) && defined(HAVE_CHACHA) && \
  2005. defined(HAVE_POLY1305)
  2006. #include <wolfssl/wolfcrypt/chacha20_poly1305.h>
  2007. typedef struct key_ctx {
  2008. byte name[WOLFSSL_TICKET_NAME_SZ]; /* name for this context */
  2009. byte key[CHACHA20_POLY1305_AEAD_KEYSIZE]; /* cipher key */
  2010. } key_ctx;
  2011. static key_ctx myKey_ctx;
  2012. static WC_RNG myKey_rng;
  2013. static INLINE int TicketInit(void)
  2014. {
  2015. int ret = wc_InitRng(&myKey_rng);
  2016. if (ret != 0) return ret;
  2017. ret = wc_RNG_GenerateBlock(&myKey_rng, myKey_ctx.key, sizeof(myKey_ctx.key));
  2018. if (ret != 0) return ret;
  2019. ret = wc_RNG_GenerateBlock(&myKey_rng, myKey_ctx.name,sizeof(myKey_ctx.name));
  2020. if (ret != 0) return ret;
  2021. return 0;
  2022. }
  2023. static INLINE void TicketCleanup(void)
  2024. {
  2025. wc_FreeRng(&myKey_rng);
  2026. }
  2027. static INLINE int myTicketEncCb(WOLFSSL* ssl,
  2028. byte key_name[WOLFSSL_TICKET_NAME_SZ],
  2029. byte iv[WOLFSSL_TICKET_IV_SZ],
  2030. byte mac[WOLFSSL_TICKET_MAC_SZ],
  2031. int enc, byte* ticket, int inLen, int* outLen,
  2032. void* userCtx)
  2033. {
  2034. (void)ssl;
  2035. (void)userCtx;
  2036. int ret;
  2037. word16 sLen = XHTONS(inLen);
  2038. byte aad[WOLFSSL_TICKET_NAME_SZ + WOLFSSL_TICKET_IV_SZ + 2];
  2039. int aadSz = WOLFSSL_TICKET_NAME_SZ + WOLFSSL_TICKET_IV_SZ + 2;
  2040. byte* tmp = aad;
  2041. if (enc) {
  2042. XMEMCPY(key_name, myKey_ctx.name, WOLFSSL_TICKET_NAME_SZ);
  2043. ret = wc_RNG_GenerateBlock(&myKey_rng, iv, WOLFSSL_TICKET_IV_SZ);
  2044. if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
  2045. /* build aad from key name, iv, and length */
  2046. XMEMCPY(tmp, key_name, WOLFSSL_TICKET_NAME_SZ);
  2047. tmp += WOLFSSL_TICKET_NAME_SZ;
  2048. XMEMCPY(tmp, iv, WOLFSSL_TICKET_IV_SZ);
  2049. tmp += WOLFSSL_TICKET_IV_SZ;
  2050. XMEMCPY(tmp, &sLen, 2);
  2051. ret = wc_ChaCha20Poly1305_Encrypt(myKey_ctx.key, iv,
  2052. aad, aadSz,
  2053. ticket, inLen,
  2054. ticket,
  2055. mac);
  2056. if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
  2057. *outLen = inLen; /* no padding in this mode */
  2058. } else {
  2059. /* decrypt */
  2060. /* see if we know this key */
  2061. if (XMEMCMP(key_name, myKey_ctx.name, WOLFSSL_TICKET_NAME_SZ) != 0){
  2062. printf("client presented unknown ticket key name ");
  2063. return WOLFSSL_TICKET_RET_FATAL;
  2064. }
  2065. /* build aad from key name, iv, and length */
  2066. XMEMCPY(tmp, key_name, WOLFSSL_TICKET_NAME_SZ);
  2067. tmp += WOLFSSL_TICKET_NAME_SZ;
  2068. XMEMCPY(tmp, iv, WOLFSSL_TICKET_IV_SZ);
  2069. tmp += WOLFSSL_TICKET_IV_SZ;
  2070. XMEMCPY(tmp, &sLen, 2);
  2071. ret = wc_ChaCha20Poly1305_Decrypt(myKey_ctx.key, iv,
  2072. aad, aadSz,
  2073. ticket, inLen,
  2074. mac,
  2075. ticket);
  2076. if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
  2077. *outLen = inLen; /* no padding in this mode */
  2078. }
  2079. return WOLFSSL_TICKET_RET_OK;
  2080. }
  2081. #endif /* HAVE_SESSION_TICKET && CHACHA20 && POLY1305 */
  2082. static INLINE word16 GetRandomPort(void)
  2083. {
  2084. word16 port = 0;
  2085. /* Generate random port for testing */
  2086. WC_RNG rng;
  2087. if (wc_InitRng(&rng) == 0) {
  2088. wc_RNG_GenerateBlock(&rng, (byte*)&port, sizeof(port));
  2089. port |= 0xC000; /* Make sure its in the 49152 - 65535 range */
  2090. wc_FreeRng(&rng);
  2091. }
  2092. return port;
  2093. }
  2094. #endif /* wolfSSL_TEST_H */