test.h 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122
  1. /* test.h */
  2. #ifndef wolfSSL_TEST_H
  3. #define wolfSSL_TEST_H
  4. #ifdef FUSION_RTOS
  5. #include <fclstdio.h>
  6. #include <fclstdlib.h>
  7. #else
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #endif
  11. #include <assert.h>
  12. #include <ctype.h>
  13. #include <wolfssl/wolfcrypt/types.h>
  14. #include <wolfssl/wolfcrypt/error-crypt.h>
  15. #include <wolfssl/wolfcrypt/random.h>
  16. #include <wolfssl/wolfcrypt/mem_track.h>
  17. #if defined(SHOW_CERTS) && \
  18. (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL))
  19. #include <wolfssl/wolfcrypt/asn.h> /* for domain component NID value */
  20. #endif
  21. #ifdef ATOMIC_USER
  22. #include <wolfssl/wolfcrypt/aes.h>
  23. #include <wolfssl/wolfcrypt/arc4.h>
  24. #include <wolfssl/wolfcrypt/hmac.h>
  25. #endif
  26. #ifdef HAVE_PK_CALLBACKS
  27. #include <wolfssl/wolfcrypt/asn.h>
  28. #ifndef NO_RSA
  29. #include <wolfssl/wolfcrypt/rsa.h>
  30. #endif
  31. #ifdef HAVE_ECC
  32. #include <wolfssl/wolfcrypt/ecc.h>
  33. #endif /* HAVE_ECC */
  34. #ifndef NO_DH
  35. #include <wolfssl/wolfcrypt/dh.h>
  36. #endif /* !NO_DH */
  37. #ifdef HAVE_ED25519
  38. #include <wolfssl/wolfcrypt/ed25519.h>
  39. #endif /* HAVE_ED25519 */
  40. #ifdef HAVE_CURVE25519
  41. #include <wolfssl/wolfcrypt/curve25519.h>
  42. #endif /* HAVE_ECC */
  43. #ifdef HAVE_ED448
  44. #include <wolfssl/wolfcrypt/ed448.h>
  45. #endif /* HAVE_ED448 */
  46. #ifdef HAVE_CURVE448
  47. #include <wolfssl/wolfcrypt/curve448.h>
  48. #endif /* HAVE_ECC */
  49. #endif /*HAVE_PK_CALLBACKS */
  50. #ifdef USE_WINDOWS_API
  51. #include <winsock2.h>
  52. #include <process.h>
  53. #ifdef TEST_IPV6 /* don't require newer SDK for IPV4 */
  54. #include <ws2tcpip.h>
  55. #include <wspiapi.h>
  56. #endif
  57. #define SOCKET_T SOCKET
  58. #define SNPRINTF _snprintf
  59. #define XSLEEP_MS(t) Sleep(t)
  60. #elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
  61. #include <string.h>
  62. #include "rl_net.h"
  63. #define SOCKET_T int
  64. typedef int socklen_t ;
  65. #define inet_addr wolfSSL_inet_addr
  66. static unsigned long wolfSSL_inet_addr(const char *cp)
  67. {
  68. unsigned int a[4] ; unsigned long ret ;
  69. sscanf(cp, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3]) ;
  70. ret = ((a[3]<<24) + (a[2]<<16) + (a[1]<<8) + a[0]) ;
  71. return(ret) ;
  72. }
  73. #if defined(HAVE_KEIL_RTX)
  74. #define XSLEEP_MS(t) os_dly_wait(t)
  75. #elif defined(WOLFSSL_CMSIS_RTOS) || defined(WOLFSSL_CMSIS_RTOSv2)
  76. #define XSLEEP_MS(t) osDelay(t)
  77. #endif
  78. #elif defined(WOLFSSL_TIRTOS)
  79. #include <string.h>
  80. #include <netdb.h>
  81. #include <sys/types.h>
  82. #include <arpa/inet.h>
  83. #include <sys/socket.h>
  84. #include <ti/sysbios/knl/Task.h>
  85. struct hostent {
  86. char *h_name; /* official name of host */
  87. char **h_aliases; /* alias list */
  88. int h_addrtype; /* host address type */
  89. int h_length; /* length of address */
  90. char **h_addr_list; /* list of addresses from name server */
  91. };
  92. #define SOCKET_T int
  93. #define XSLEEP_MS(t) Task_sleep(t/1000)
  94. #elif defined(WOLFSSL_VXWORKS)
  95. #include <hostLib.h>
  96. #include <sockLib.h>
  97. #include <arpa/inet.h>
  98. #include <string.h>
  99. #include <selectLib.h>
  100. #include <sys/types.h>
  101. #include <netinet/in.h>
  102. #include <fcntl.h>
  103. #include <sys/time.h>
  104. #include <netdb.h>
  105. #include <pthread.h>
  106. #define SOCKET_T int
  107. #elif defined(WOLFSSL_ZEPHYR)
  108. #include <string.h>
  109. #include <sys/types.h>
  110. #include <net/socket.h>
  111. #define SOCKET_T int
  112. #define SOL_SOCKET 1
  113. #define SO_REUSEADDR 201
  114. #define WOLFSSL_USE_GETADDRINFO
  115. static unsigned long inet_addr(const char *cp)
  116. {
  117. unsigned int a[4]; unsigned long ret;
  118. int i, j;
  119. for (i=0, j=0; i<4; i++) {
  120. a[i] = 0;
  121. while (cp[j] != '.' && cp[j] != '\0') {
  122. a[i] *= 10;
  123. a[i] += cp[j] - '0';
  124. j++;
  125. }
  126. }
  127. ret = ((a[3]<<24) + (a[2]<<16) + (a[1]<<8) + a[0]) ;
  128. return(ret) ;
  129. }
  130. #else
  131. #include <string.h>
  132. #include <sys/types.h>
  133. #ifndef WOLFSSL_LEANPSK
  134. #include <unistd.h>
  135. #include <netdb.h>
  136. #include <netinet/in.h>
  137. #include <netinet/tcp.h>
  138. #include <arpa/inet.h>
  139. #include <sys/ioctl.h>
  140. #include <sys/time.h>
  141. #include <sys/socket.h>
  142. #include <pthread.h>
  143. #include <fcntl.h>
  144. #ifdef TEST_IPV6
  145. #include <netdb.h>
  146. #endif
  147. #endif
  148. #ifdef FREESCALE_MQX
  149. typedef int socklen_t ;
  150. #endif
  151. #define SOCKET_T int
  152. #ifndef SO_NOSIGPIPE
  153. #include <signal.h> /* ignore SIGPIPE */
  154. #endif
  155. #define SNPRINTF snprintf
  156. #define XSELECT_WAIT(x,y) do { \
  157. struct timeval tv = {(x),(y)}; \
  158. select(0, NULL, NULL, NULL, &tv); \
  159. } while (0)
  160. #define XSLEEP_US(u) XSELECT_WAIT(0,u)
  161. #define XSLEEP_MS(m) XSELECT_WAIT(0,(m)*1000)
  162. #endif /* USE_WINDOWS_API */
  163. #ifndef XSLEEP_MS
  164. #define XSLEEP_MS(t) sleep(t/1000)
  165. #endif
  166. #ifdef WOLFSSL_ASYNC_CRYPT
  167. #include <wolfssl/wolfcrypt/async.h>
  168. #endif
  169. #ifdef HAVE_CAVIUM
  170. #include <wolfssl/wolfcrypt/port/cavium/cavium_nitrox.h>
  171. #endif
  172. #ifdef _MSC_VER
  173. /* disable conversion warning */
  174. /* 4996 warning to use MS extensions e.g., strcpy_s instead of strncpy */
  175. #pragma warning(disable:4244 4996)
  176. #endif
  177. #ifndef WOLFSSL_CIPHER_LIST_MAX_SIZE
  178. #define WOLFSSL_CIPHER_LIST_MAX_SIZE 4096
  179. #endif
  180. /* Buffer for benchmark tests */
  181. #ifndef TEST_BUFFER_SIZE
  182. #define TEST_BUFFER_SIZE 16384
  183. #endif
  184. #ifndef WOLFSSL_HAVE_MIN
  185. #define WOLFSSL_HAVE_MIN
  186. static WC_INLINE word32 min(word32 a, word32 b)
  187. {
  188. return a > b ? b : a;
  189. }
  190. #endif /* WOLFSSL_HAVE_MIN */
  191. /* Socket Handling */
  192. #ifndef WOLFSSL_SOCKET_INVALID
  193. #ifdef USE_WINDOWS_API
  194. #define WOLFSSL_SOCKET_INVALID ((SOCKET_T)INVALID_SOCKET)
  195. #elif defined(WOLFSSL_TIRTOS)
  196. #define WOLFSSL_SOCKET_INVALID ((SOCKET_T)-1)
  197. #else
  198. #define WOLFSSL_SOCKET_INVALID (SOCKET_T)(0)
  199. #endif
  200. #endif /* WOLFSSL_SOCKET_INVALID */
  201. #ifndef WOLFSSL_SOCKET_IS_INVALID
  202. #if defined(USE_WINDOWS_API) || defined(WOLFSSL_TIRTOS)
  203. #define WOLFSSL_SOCKET_IS_INVALID(s) ((SOCKET_T)(s) == WOLFSSL_SOCKET_INVALID)
  204. #else
  205. #define WOLFSSL_SOCKET_IS_INVALID(s) ((SOCKET_T)(s) < WOLFSSL_SOCKET_INVALID)
  206. #endif
  207. #endif /* WOLFSSL_SOCKET_IS_INVALID */
  208. #if defined(__MACH__) || defined(USE_WINDOWS_API)
  209. #ifndef _SOCKLEN_T
  210. typedef int socklen_t;
  211. #endif
  212. #endif
  213. /* HPUX doesn't use socklent_t for third parameter to accept, unless
  214. _XOPEN_SOURCE_EXTENDED is defined */
  215. #if !defined(__hpux__) && !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_IAR_ARM)\
  216. && !defined(WOLFSSL_ROWLEY_ARM) && !defined(WOLFSSL_KEIL_TCP_NET)
  217. typedef socklen_t* ACCEPT_THIRD_T;
  218. #else
  219. #if defined _XOPEN_SOURCE_EXTENDED
  220. typedef socklen_t* ACCEPT_THIRD_T;
  221. #else
  222. typedef int* ACCEPT_THIRD_T;
  223. #endif
  224. #endif
  225. #ifdef SINGLE_THREADED
  226. typedef unsigned int THREAD_RETURN;
  227. typedef void* THREAD_TYPE;
  228. #define WOLFSSL_THREAD
  229. #else
  230. #if defined(_POSIX_THREADS) && !defined(__MINGW32__)
  231. typedef void* THREAD_RETURN;
  232. typedef pthread_t THREAD_TYPE;
  233. #define WOLFSSL_THREAD
  234. #define INFINITE -1
  235. #define WAIT_OBJECT_0 0L
  236. #elif defined(WOLFSSL_MDK_ARM)|| defined(WOLFSSL_KEIL_TCP_NET) || defined(FREESCALE_MQX)
  237. typedef unsigned int THREAD_RETURN;
  238. typedef int THREAD_TYPE;
  239. #define WOLFSSL_THREAD
  240. #elif defined(WOLFSSL_TIRTOS)
  241. typedef void THREAD_RETURN;
  242. typedef Task_Handle THREAD_TYPE;
  243. #define WOLFSSL_THREAD
  244. #elif defined(WOLFSSL_ZEPHYR)
  245. typedef void THREAD_RETURN;
  246. typedef struct k_thread THREAD_TYPE;
  247. #define WOLFSSL_THREAD
  248. #else
  249. typedef unsigned int THREAD_RETURN;
  250. typedef intptr_t THREAD_TYPE;
  251. #define WOLFSSL_THREAD __stdcall
  252. #endif
  253. #endif
  254. #ifdef TEST_IPV6
  255. typedef struct sockaddr_in6 SOCKADDR_IN_T;
  256. #define AF_INET_V AF_INET6
  257. #else
  258. typedef struct sockaddr_in SOCKADDR_IN_T;
  259. #define AF_INET_V AF_INET
  260. #endif
  261. #ifndef WOLFSSL_NO_TLS12
  262. #define SERVER_DEFAULT_VERSION 3
  263. #else
  264. #define SERVER_DEFAULT_VERSION 4
  265. #endif
  266. #define SERVER_DTLS_DEFAULT_VERSION (-2)
  267. #define SERVER_INVALID_VERSION (-99)
  268. #define SERVER_DOWNGRADE_VERSION (-98)
  269. #ifndef WOLFSSL_NO_TLS12
  270. #define CLIENT_DEFAULT_VERSION 3
  271. #else
  272. #define CLIENT_DEFAULT_VERSION 4
  273. #endif
  274. #define CLIENT_DTLS_DEFAULT_VERSION (-2)
  275. #define CLIENT_INVALID_VERSION (-99)
  276. #define CLIENT_DOWNGRADE_VERSION (-98)
  277. #define EITHER_DOWNGRADE_VERSION (-97)
  278. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_MAX_STRENGTH)
  279. #define DEFAULT_MIN_DHKEY_BITS 2048
  280. #define DEFAULT_MAX_DHKEY_BITS 3072
  281. #else
  282. #define DEFAULT_MIN_DHKEY_BITS 1024
  283. #define DEFAULT_MAX_DHKEY_BITS 2048
  284. #endif
  285. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_MAX_STRENGTH)
  286. #define DEFAULT_MIN_RSAKEY_BITS 2048
  287. #else
  288. #ifndef DEFAULT_MIN_RSAKEY_BITS
  289. #define DEFAULT_MIN_RSAKEY_BITS 1024
  290. #endif
  291. #endif
  292. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_MAX_STRENGTH)
  293. #define DEFAULT_MIN_ECCKEY_BITS 256
  294. #else
  295. #ifndef DEFAULT_MIN_ECCKEY_BITS
  296. #define DEFAULT_MIN_ECCKEY_BITS 224
  297. #endif
  298. #endif
  299. /* all certs relative to wolfSSL home directory now */
  300. #if defined(WOLFSSL_NO_CURRDIR) || defined(WOLFSSL_MDK_SHELL)
  301. #define caCertFile "certs/ca-cert.pem"
  302. #define eccCertFile "certs/server-ecc.pem"
  303. #define eccKeyFile "certs/ecc-key.pem"
  304. #define eccRsaCertFile "certs/server-ecc-rsa.pem"
  305. #define svrCertFile "certs/server-cert.pem"
  306. #define svrKeyFile "certs/server-key.pem"
  307. #define cliCertFile "certs/client-cert.pem"
  308. #define cliCertDerFile "certs/client-cert.der"
  309. #define cliCertFileExt "certs/client-cert-ext.pem"
  310. #define cliCertDerFileExt "certs/client-cert-ext.der"
  311. #define cliKeyFile "certs/client-key.pem"
  312. #define ntruCertFile "certs/ntru-cert.pem"
  313. #define ntruKeyFile "certs/ntru-key.raw"
  314. #define dhParamFile "certs/dh2048.pem"
  315. #define cliEccKeyFile "certs/ecc-client-key.pem"
  316. #define cliEccCertFile "certs/client-ecc-cert.pem"
  317. #define caEccCertFile "certs/ca-ecc-cert.pem"
  318. #define crlPemDir "certs/crl"
  319. #define edCertFile "certs/ed25519/server-ed25519-cert.pem"
  320. #define edKeyFile "certs/ed25519/server-ed25519-priv.pem"
  321. #define cliEdCertFile "certs/ed25519/client-ed25519.pem"
  322. #define cliEdKeyFile "certs/ed25519/client-ed25519-priv.pem"
  323. #define caEdCertFile "certs/ed25519/ca-ed25519.pem"
  324. #define ed448CertFile "certs/ed448/server-ed448-cert.pem"
  325. #define ed448KeyFile "certs/ed448/server-ed448-priv.pem"
  326. #define cliEd448CertFile "certs/ed448/client-ed448.pem"
  327. #define cliEd448KeyFile "certs/ed448/client-ed448-priv.pem"
  328. #define caEd448CertFile "certs/ed448/ca-ed448.pem"
  329. #define caCertFolder "certs/"
  330. #ifdef HAVE_WNR
  331. /* Whitewood netRandom default config file */
  332. #define wnrConfig "wnr-example.conf"
  333. #endif
  334. #else
  335. #define caCertFile "./certs/ca-cert.pem"
  336. #define eccCertFile "./certs/server-ecc.pem"
  337. #define eccKeyFile "./certs/ecc-key.pem"
  338. #define eccRsaCertFile "./certs/server-ecc-rsa.pem"
  339. #define svrCertFile "./certs/server-cert.pem"
  340. #define svrKeyFile "./certs/server-key.pem"
  341. #define cliCertFile "./certs/client-cert.pem"
  342. #define cliCertDerFile "./certs/client-cert.der"
  343. #define cliCertFileExt "./certs/client-cert-ext.pem"
  344. #define cliCertDerFileExt "./certs/client-cert-ext.der"
  345. #define cliKeyFile "./certs/client-key.pem"
  346. #define ntruCertFile "./certs/ntru-cert.pem"
  347. #define ntruKeyFile "./certs/ntru-key.raw"
  348. #define dhParamFile "./certs/dh2048.pem"
  349. #define cliEccKeyFile "./certs/ecc-client-key.pem"
  350. #define cliEccCertFile "./certs/client-ecc-cert.pem"
  351. #define caEccCertFile "./certs/ca-ecc-cert.pem"
  352. #define crlPemDir "./certs/crl"
  353. #define edCertFile "./certs/ed25519/server-ed25519-cert.pem"
  354. #define edKeyFile "./certs/ed25519/server-ed25519-priv.pem"
  355. #define cliEdCertFile "./certs/ed25519/client-ed25519.pem"
  356. #define cliEdKeyFile "./certs/ed25519/client-ed25519-priv.pem"
  357. #define caEdCertFile "./certs/ed25519/ca-ed25519.pem"
  358. #define ed448CertFile "./certs/ed448/server-ed448-cert.pem"
  359. #define ed448KeyFile "./certs/ed448/server-ed448-priv.pem"
  360. #define cliEd448CertFile "./certs/ed448/client-ed448.pem"
  361. #define cliEd448KeyFile "./certs/ed448/client-ed448-priv.pem"
  362. #define caEd448CertFile "./certs/ed448/ca-ed448.pem"
  363. #define caCertFolder "./certs/"
  364. #ifdef HAVE_WNR
  365. /* Whitewood netRandom default config file */
  366. #define wnrConfig "./wnr-example.conf"
  367. #endif
  368. #endif
  369. typedef struct tcp_ready {
  370. word16 ready; /* predicate */
  371. word16 port;
  372. char* srfName; /* server ready file name */
  373. #if defined(_POSIX_THREADS) && !defined(__MINGW32__)
  374. pthread_mutex_t mutex;
  375. pthread_cond_t cond;
  376. #endif
  377. } tcp_ready;
  378. static WC_INLINE void InitTcpReady(tcp_ready* ready)
  379. {
  380. ready->ready = 0;
  381. ready->port = 0;
  382. ready->srfName = NULL;
  383. #ifdef SINGLE_THREADED
  384. #elif defined(_POSIX_THREADS) && !defined(__MINGW32__)
  385. pthread_mutex_init(&ready->mutex, 0);
  386. pthread_cond_init(&ready->cond, 0);
  387. #endif
  388. }
  389. static WC_INLINE void FreeTcpReady(tcp_ready* ready)
  390. {
  391. #ifdef SINGLE_THREADED
  392. (void)ready;
  393. #elif defined(_POSIX_THREADS) && !defined(__MINGW32__)
  394. pthread_mutex_destroy(&ready->mutex);
  395. pthread_cond_destroy(&ready->cond);
  396. #else
  397. (void)ready;
  398. #endif
  399. }
  400. typedef WOLFSSL_METHOD* (*method_provider)(void);
  401. typedef void (*ctx_callback)(WOLFSSL_CTX* ctx);
  402. typedef void (*ssl_callback)(WOLFSSL* ssl);
  403. typedef struct callback_functions {
  404. method_provider method;
  405. ctx_callback ctx_ready;
  406. ssl_callback ssl_ready;
  407. ssl_callback on_result;
  408. WOLFSSL_CTX* ctx;
  409. unsigned char isSharedCtx:1;
  410. } callback_functions;
  411. typedef struct func_args {
  412. int argc;
  413. char** argv;
  414. int return_code;
  415. tcp_ready* signal;
  416. callback_functions *callbacks;
  417. } func_args;
  418. void wait_tcp_ready(func_args*);
  419. #ifdef WOLFSSL_ZEPHYR
  420. typedef void THREAD_FUNC(void*, void*, void*);
  421. #else
  422. typedef THREAD_RETURN WOLFSSL_THREAD THREAD_FUNC(void*);
  423. #endif
  424. void start_thread(THREAD_FUNC, func_args*, THREAD_TYPE*);
  425. void join_thread(THREAD_TYPE);
  426. /* wolfSSL */
  427. #ifndef TEST_IPV6
  428. static const char* const wolfSSLIP = "127.0.0.1";
  429. #else
  430. static const char* const wolfSSLIP = "::1";
  431. #endif
  432. static const word16 wolfSSLPort = 11111;
  433. #ifndef MY_EX_USAGE
  434. #define MY_EX_USAGE 2
  435. #endif
  436. #ifndef EXIT_FAILURE
  437. #define EXIT_FAILURE 1
  438. #endif
  439. #if defined(WOLFSSL_FORCE_MALLOC_FAIL_TEST) || defined(WOLFSSL_ZEPHYR)
  440. #ifndef EXIT_SUCCESS
  441. #define EXIT_SUCCESS 0
  442. #endif
  443. #define XEXIT(rc) return rc
  444. #define XEXIT_T(rc) return (THREAD_RETURN)rc
  445. #else
  446. #define XEXIT(rc) exit((int)(rc))
  447. #define XEXIT_T(rc) exit((int)(rc))
  448. #endif
  449. static WC_INLINE
  450. #if defined(WOLFSSL_FORCE_MALLOC_FAIL_TEST) || defined(WOLFSSL_ZEPHYR)
  451. THREAD_RETURN
  452. #else
  453. WC_NORETURN void
  454. #endif
  455. err_sys(const char* msg)
  456. {
  457. #if !defined(__GNUC__)
  458. /* scan-build (which pretends to be gnuc) can get confused and think the
  459. * msg pointer can be null even when hardcoded and then it won't exit,
  460. * making null pointer checks above the err_sys() call useless.
  461. * We could just always exit() but some compilers will complain about no
  462. * possible return, with gcc we know the attribute to handle that with
  463. * WC_NORETURN. */
  464. if (msg)
  465. #endif
  466. {
  467. printf("wolfSSL error: %s\n", msg);
  468. XEXIT_T(EXIT_FAILURE);
  469. }
  470. }
  471. static WC_INLINE
  472. #if defined(WOLFSSL_FORCE_MALLOC_FAIL_TEST) || defined(WOLFSSL_ZEPHYR)
  473. THREAD_RETURN
  474. #else
  475. WC_NORETURN void
  476. #endif
  477. err_sys_with_errno(const char* msg)
  478. {
  479. #if !defined(__GNUC__)
  480. /* scan-build (which pretends to be gnuc) can get confused and think the
  481. * msg pointer can be null even when hardcoded and then it won't exit,
  482. * making null pointer checks above the err_sys() call useless.
  483. * We could just always exit() but some compilers will complain about no
  484. * possible return, with gcc we know the attribute to handle that with
  485. * WC_NORETURN. */
  486. if (msg)
  487. #endif
  488. {
  489. #if defined(HAVE_STRING_H) && defined(HAVE_ERRNO_H)
  490. printf("wolfSSL error: %s: %s\n", msg, strerror(errno));
  491. #else
  492. printf("wolfSSL error: %s\n", msg);
  493. #endif
  494. XEXIT_T(EXIT_FAILURE);
  495. }
  496. }
  497. extern int myoptind;
  498. extern char* myoptarg;
  499. /**
  500. *
  501. * @param argc Number of argv strings
  502. * @param argv Array of string arguments
  503. * @param optstring String containing the supported alphanumeric arguments.
  504. * A ':' following a character means that it requires a
  505. * value in myoptarg to be set. A ';' means that the
  506. * myoptarg is optional. myoptarg is set to "" if not
  507. * present.
  508. * @return Option letter in argument
  509. */
  510. static WC_INLINE int mygetopt(int argc, char** argv, const char* optstring)
  511. {
  512. static char* next = NULL;
  513. char c;
  514. char* cp;
  515. /* Added sanity check becuase scan-build complains argv[myoptind] access
  516. * results in a null pointer dereference. */
  517. if (argv == NULL) {
  518. myoptarg = NULL;
  519. return -1;
  520. }
  521. if (myoptind == 0)
  522. next = NULL; /* we're starting new/over */
  523. if (next == NULL || *next == '\0') {
  524. if (myoptind == 0)
  525. myoptind++;
  526. if (myoptind >= argc || argv[myoptind] == NULL ||
  527. argv[myoptind][0] != '-' || argv[myoptind][1] == '\0') {
  528. myoptarg = NULL;
  529. if (myoptind < argc)
  530. myoptarg = argv[myoptind];
  531. return -1;
  532. }
  533. if (strcmp(argv[myoptind], "--") == 0) {
  534. myoptind++;
  535. myoptarg = NULL;
  536. if (myoptind < argc)
  537. myoptarg = argv[myoptind];
  538. return -1;
  539. }
  540. next = argv[myoptind];
  541. next++; /* skip - */
  542. myoptind++;
  543. }
  544. c = *next++;
  545. /* The C++ strchr can return a different value */
  546. cp = (char*)strchr(optstring, c);
  547. if (cp == NULL || c == ':' || c == ';')
  548. return '?';
  549. cp++;
  550. if (*cp == ':') {
  551. if (*next != '\0') {
  552. myoptarg = next;
  553. next = NULL;
  554. }
  555. else if (myoptind < argc) {
  556. myoptarg = argv[myoptind];
  557. myoptind++;
  558. }
  559. else
  560. return '?';
  561. }
  562. else if (*cp == ';') {
  563. myoptarg = (char*)"";
  564. if (*next != '\0') {
  565. myoptarg = next;
  566. next = NULL;
  567. }
  568. else if (myoptind < argc) {
  569. /* Check if next argument is not a parameter argument */
  570. if (argv[myoptind] && argv[myoptind][0] != '-') {
  571. myoptarg = argv[myoptind];
  572. myoptind++;
  573. }
  574. }
  575. }
  576. return c;
  577. }
  578. #ifdef WOLFSSL_ENCRYPTED_KEYS
  579. static WC_INLINE int PasswordCallBack(char* passwd, int sz, int rw, void* userdata)
  580. {
  581. (void)rw;
  582. (void)userdata;
  583. if (userdata != NULL) {
  584. strncpy(passwd, (char*)userdata, sz);
  585. return (int)XSTRLEN((char*)userdata);
  586. }
  587. else {
  588. strncpy(passwd, "yassl123", sz);
  589. return 8;
  590. }
  591. }
  592. #endif
  593. static const char* client_showpeer_msg[][8] = {
  594. /* English */
  595. {
  596. "SSL version is",
  597. "SSL cipher suite is",
  598. "SSL curve name is",
  599. "SSL DH size is",
  600. "SSL reused session",
  601. "Alternate cert chain used",
  602. "peer's cert info:",
  603. NULL
  604. },
  605. #ifndef NO_MULTIBYTE_PRINT
  606. /* Japanese */
  607. {
  608. "SSL バージョンは",
  609. "SSL 暗号スイートは",
  610. "SSL 曲線名は",
  611. "SSL DH サイズは",
  612. "SSL 再利用セッション",
  613. "代替証明チェーンを使用",
  614. "相手方証明書情報",
  615. NULL
  616. },
  617. #endif
  618. };
  619. #if defined(KEEP_PEER_CERT) || defined(KEEP_OUR_CERT) || defined(SESSION_CERTS)
  620. static const char* client_showx509_msg[][5] = {
  621. /* English */
  622. {
  623. "issuer",
  624. "subject",
  625. "altname",
  626. "serial number",
  627. NULL
  628. },
  629. #ifndef NO_MULTIBYTE_PRINT
  630. /* Japanese */
  631. {
  632. "発行者",
  633. "サブジェクト",
  634. "代替名",
  635. "シリアル番号",
  636. NULL
  637. },
  638. #endif
  639. };
  640. /* lng_index is to specify the language for displaying message. */
  641. /* 0:English, 1:Japanese */
  642. static WC_INLINE void ShowX509Ex(WOLFSSL_X509* x509, const char* hdr,
  643. int lng_index)
  644. {
  645. char* altName;
  646. char* issuer;
  647. char* subject;
  648. byte serial[32];
  649. int ret;
  650. int sz = sizeof(serial);
  651. const char** words = client_showx509_msg[lng_index];
  652. if (x509 == NULL) {
  653. printf("%s No Cert\n", hdr);
  654. return;
  655. }
  656. issuer = wolfSSL_X509_NAME_oneline(
  657. wolfSSL_X509_get_issuer_name(x509), 0, 0);
  658. subject = wolfSSL_X509_NAME_oneline(
  659. wolfSSL_X509_get_subject_name(x509), 0, 0);
  660. printf("%s\n %s : %s\n %s: %s\n", hdr, words[0], issuer, words[1], subject);
  661. while ( (altName = wolfSSL_X509_get_next_altname(x509)) != NULL)
  662. printf(" %s = %s\n", words[2], altName);
  663. ret = wolfSSL_X509_get_serial_number(x509, serial, &sz);
  664. if (ret == WOLFSSL_SUCCESS) {
  665. int i;
  666. int strLen;
  667. char serialMsg[80];
  668. /* testsuite has multiple threads writing to stdout, get output
  669. message ready to write once */
  670. strLen = sprintf(serialMsg, " %s", words[3]);
  671. for (i = 0; i < sz; i++)
  672. sprintf(serialMsg + strLen + (i*3), ":%02x ", serial[i]);
  673. printf("%s\n", serialMsg);
  674. }
  675. XFREE(subject, 0, DYNAMIC_TYPE_OPENSSL);
  676. XFREE(issuer, 0, DYNAMIC_TYPE_OPENSSL);
  677. #if defined(SHOW_CERTS) && defined(OPENSSL_EXTRA)
  678. {
  679. WOLFSSL_BIO* bio;
  680. char buf[256]; /* should be size of ASN_NAME_MAX */
  681. int textSz;
  682. /* print out domain component if certificate has it */
  683. textSz = wolfSSL_X509_NAME_get_text_by_NID(
  684. wolfSSL_X509_get_subject_name(x509), NID_domainComponent,
  685. buf, sizeof(buf));
  686. if (textSz > 0) {
  687. printf("Domain Component = %s\n", buf);
  688. }
  689. bio = wolfSSL_BIO_new(wolfSSL_BIO_s_file());
  690. if (bio != NULL) {
  691. wolfSSL_BIO_set_fp(bio, stdout, BIO_NOCLOSE);
  692. wolfSSL_X509_print(bio, x509);
  693. wolfSSL_BIO_free(bio);
  694. }
  695. }
  696. #endif /* SHOW_CERTS && OPENSSL_EXTRA */
  697. }
  698. /* original ShowX509 to maintain compatibility */
  699. static WC_INLINE void ShowX509(WOLFSSL_X509* x509, const char* hdr)
  700. {
  701. ShowX509Ex(x509, hdr, 0);
  702. }
  703. #endif /* KEEP_PEER_CERT || KEEP_OUR_CERT || SESSION_CERTS */
  704. #if defined(SHOW_CERTS) && defined(SESSION_CERTS) && \
  705. (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL))
  706. static WC_INLINE void ShowX509Chain(WOLFSSL_X509_CHAIN* chain, int count,
  707. const char* hdr)
  708. {
  709. int i;
  710. int length;
  711. unsigned char buffer[3072];
  712. WOLFSSL_X509* chainX509;
  713. for (i = 0; i < count; i++) {
  714. wolfSSL_get_chain_cert_pem(chain, i, buffer, sizeof(buffer), &length);
  715. buffer[length] = 0;
  716. printf("\n%s: %d has length %d data = \n%s\n", hdr, i, length, buffer);
  717. chainX509 = wolfSSL_get_chain_X509(chain, i);
  718. if (chainX509)
  719. ShowX509(chainX509, hdr);
  720. else
  721. printf("get_chain_X509 failed\n");
  722. wolfSSL_FreeX509(chainX509);
  723. }
  724. }
  725. #endif /* SHOW_CERTS && SESSION_CERTS */
  726. /* lng_index is to specify the language for displaying message. */
  727. /* 0:English, 1:Japanese */
  728. static WC_INLINE void showPeerEx(WOLFSSL* ssl, int lng_index)
  729. {
  730. WOLFSSL_CIPHER* cipher;
  731. const char** words = client_showpeer_msg[lng_index];
  732. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) || \
  733. !defined(NO_DH)
  734. const char *name;
  735. #endif
  736. #ifndef NO_DH
  737. int bits;
  738. #endif
  739. #ifdef KEEP_PEER_CERT
  740. WOLFSSL_X509* peer = wolfSSL_get_peer_certificate(ssl);
  741. if (peer)
  742. ShowX509Ex(peer, words[6], lng_index);
  743. else
  744. printf("peer has no cert!\n");
  745. wolfSSL_FreeX509(peer);
  746. #endif
  747. #if defined(SHOW_CERTS) && defined(KEEP_OUR_CERT) && \
  748. (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL))
  749. ShowX509(wolfSSL_get_certificate(ssl), "our cert info:");
  750. printf("Peer verify result = %lu\n", wolfSSL_get_verify_result(ssl));
  751. #endif /* SHOW_CERTS && KEEP_OUR_CERT */
  752. printf("%s %s\n", words[0], wolfSSL_get_version(ssl));
  753. cipher = wolfSSL_get_current_cipher(ssl);
  754. #ifdef HAVE_QSH
  755. printf("%s %s%s\n", words[1], (wolfSSL_isQSH(ssl))? "QSH:": "",
  756. wolfSSL_CIPHER_get_name(cipher));
  757. #else
  758. printf("%s %s\n", words[1], wolfSSL_CIPHER_get_name(cipher));
  759. #endif
  760. #if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448) || \
  761. !defined(NO_DH)
  762. if ((name = wolfSSL_get_curve_name(ssl)) != NULL)
  763. printf("%s %s\n", words[2], name);
  764. #endif
  765. #ifndef NO_DH
  766. else if ((bits = wolfSSL_GetDhKey_Sz(ssl)) > 0)
  767. printf("%s %d bits\n", words[3], bits);
  768. #endif
  769. if (wolfSSL_session_reused(ssl))
  770. printf("%s\n", words[4]);
  771. #ifdef WOLFSSL_ALT_CERT_CHAINS
  772. if (wolfSSL_is_peer_alt_cert_chain(ssl))
  773. printf("%s\n", words[5]);
  774. #endif
  775. #if defined(SHOW_CERTS) && defined(SESSION_CERTS) && \
  776. (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL))
  777. {
  778. WOLFSSL_X509_CHAIN* chain;
  779. chain = wolfSSL_get_peer_chain(ssl);
  780. ShowX509Chain(chain, wolfSSL_get_chain_count(chain), "session cert");
  781. #ifdef WOLFSSL_ALT_CERT_CHAINS
  782. if (wolfSSL_is_peer_alt_cert_chain(ssl)) {
  783. chain = wolfSSL_get_peer_alt_chain(ssl);
  784. ShowX509Chain(chain, wolfSSL_get_chain_count(chain), "alt cert");
  785. }
  786. #endif
  787. }
  788. #endif /* SHOW_CERTS && SESSION_CERTS */
  789. (void)ssl;
  790. }
  791. /* original showPeer to maintain compatibility */
  792. static WC_INLINE void showPeer(WOLFSSL* ssl)
  793. {
  794. showPeerEx(ssl, 0);
  795. }
  796. static WC_INLINE void build_addr(SOCKADDR_IN_T* addr, const char* peer,
  797. word16 port, int udp, int sctp)
  798. {
  799. int useLookup = 0;
  800. (void)useLookup;
  801. (void)udp;
  802. (void)sctp;
  803. if (addr == NULL)
  804. err_sys("invalid argument to build_addr, addr is NULL");
  805. XMEMSET(addr, 0, sizeof(SOCKADDR_IN_T));
  806. #ifndef TEST_IPV6
  807. /* peer could be in human readable form */
  808. if ( ((size_t)peer != INADDR_ANY) && isalpha((int)peer[0])) {
  809. #ifndef WOLFSSL_USE_GETADDRINFO
  810. #if defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
  811. int err;
  812. struct hostent* entry = gethostbyname(peer, &err);
  813. #elif defined(WOLFSSL_TIRTOS)
  814. struct hostent* entry = DNSGetHostByName(peer);
  815. #elif defined(WOLFSSL_VXWORKS)
  816. struct hostent* entry = (struct hostent*)hostGetByName((char*)peer);
  817. #else
  818. struct hostent* entry = gethostbyname(peer);
  819. #endif
  820. if (entry) {
  821. XMEMCPY(&addr->sin_addr.s_addr, entry->h_addr_list[0],
  822. entry->h_length);
  823. useLookup = 1;
  824. }
  825. #else
  826. struct zsock_addrinfo hints, *addrInfo;
  827. char portStr[6];
  828. XSNPRINTF(portStr, sizeof(portStr), "%d", port);
  829. memset(&hints, 0, sizeof(hints));
  830. hints.ai_family = AF_UNSPEC;
  831. hints.ai_socktype = udp ? SOCK_DGRAM : SOCK_STREAM;
  832. hints.ai_protocol = udp ? IPPROTO_UDP : IPPROTO_TCP;
  833. if (getaddrinfo((char*)peer, portStr, &hints, &addrInfo) == 0) {
  834. XMEMCPY(addr, addrInfo->ai_addr, sizeof(*addr));
  835. useLookup = 1;
  836. }
  837. #endif
  838. else
  839. err_sys("no entry for host");
  840. }
  841. #endif
  842. #ifndef TEST_IPV6
  843. #if defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET)
  844. addr->sin_family = PF_INET;
  845. #else
  846. addr->sin_family = AF_INET_V;
  847. #endif
  848. addr->sin_port = XHTONS(port);
  849. if ((size_t)peer == INADDR_ANY)
  850. addr->sin_addr.s_addr = INADDR_ANY;
  851. else {
  852. if (!useLookup)
  853. addr->sin_addr.s_addr = inet_addr(peer);
  854. }
  855. #else
  856. addr->sin6_family = AF_INET_V;
  857. addr->sin6_port = XHTONS(port);
  858. if ((size_t)peer == INADDR_ANY) {
  859. addr->sin6_addr = in6addr_any;
  860. }
  861. else {
  862. #if defined(HAVE_GETADDRINFO) || defined(WOLF_C99)
  863. struct addrinfo hints;
  864. struct addrinfo* answer = NULL;
  865. int ret;
  866. char strPort[80];
  867. XMEMSET(&hints, 0, sizeof(hints));
  868. hints.ai_family = AF_INET_V;
  869. if (udp) {
  870. hints.ai_socktype = SOCK_DGRAM;
  871. hints.ai_protocol = IPPROTO_UDP;
  872. }
  873. #ifdef WOLFSSL_SCTP
  874. else if (sctp) {
  875. hints.ai_socktype = SOCK_STREAM;
  876. hints.ai_protocol = IPPROTO_SCTP;
  877. }
  878. #endif
  879. else {
  880. hints.ai_socktype = SOCK_STREAM;
  881. hints.ai_protocol = IPPROTO_TCP;
  882. }
  883. SNPRINTF(strPort, sizeof(strPort), "%d", port);
  884. strPort[79] = '\0';
  885. ret = getaddrinfo(peer, strPort, &hints, &answer);
  886. if (ret < 0 || answer == NULL)
  887. err_sys("getaddrinfo failed");
  888. XMEMCPY(addr, answer->ai_addr, answer->ai_addrlen);
  889. freeaddrinfo(answer);
  890. #else
  891. printf("no ipv6 getaddrinfo, loopback only tests/examples\n");
  892. addr->sin6_addr = in6addr_loopback;
  893. #endif
  894. }
  895. #endif
  896. }
  897. static WC_INLINE void tcp_socket(SOCKET_T* sockfd, int udp, int sctp)
  898. {
  899. (void)sctp;
  900. if (udp)
  901. *sockfd = socket(AF_INET_V, SOCK_DGRAM, IPPROTO_UDP);
  902. #ifdef WOLFSSL_SCTP
  903. else if (sctp)
  904. *sockfd = socket(AF_INET_V, SOCK_STREAM, IPPROTO_SCTP);
  905. #endif
  906. else
  907. *sockfd = socket(AF_INET_V, SOCK_STREAM, IPPROTO_TCP);
  908. if(WOLFSSL_SOCKET_IS_INVALID(*sockfd)) {
  909. err_sys_with_errno("socket failed\n");
  910. }
  911. #ifndef USE_WINDOWS_API
  912. #ifdef SO_NOSIGPIPE
  913. {
  914. int on = 1;
  915. socklen_t len = sizeof(on);
  916. int res = setsockopt(*sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, len);
  917. if (res < 0)
  918. err_sys_with_errno("setsockopt SO_NOSIGPIPE failed\n");
  919. }
  920. #elif defined(WOLFSSL_MDK_ARM) || defined (WOLFSSL_TIRTOS) ||\
  921. defined(WOLFSSL_KEIL_TCP_NET) || defined(WOLFSSL_ZEPHYR)
  922. /* nothing to define */
  923. #else /* no S_NOSIGPIPE */
  924. signal(SIGPIPE, SIG_IGN);
  925. #endif /* S_NOSIGPIPE */
  926. #if defined(TCP_NODELAY)
  927. if (!udp && !sctp)
  928. {
  929. int on = 1;
  930. socklen_t len = sizeof(on);
  931. int res = setsockopt(*sockfd, IPPROTO_TCP, TCP_NODELAY, &on, len);
  932. if (res < 0)
  933. err_sys_with_errno("setsockopt TCP_NODELAY failed\n");
  934. }
  935. #endif
  936. #endif /* USE_WINDOWS_API */
  937. }
  938. static WC_INLINE void tcp_connect(SOCKET_T* sockfd, const char* ip, word16 port,
  939. int udp, int sctp, WOLFSSL* ssl)
  940. {
  941. SOCKADDR_IN_T addr;
  942. build_addr(&addr, ip, port, udp, sctp);
  943. if (udp) {
  944. wolfSSL_dtls_set_peer(ssl, &addr, sizeof(addr));
  945. }
  946. tcp_socket(sockfd, udp, sctp);
  947. if (!udp) {
  948. if (connect(*sockfd, (const struct sockaddr*)&addr, sizeof(addr)) != 0)
  949. err_sys_with_errno("tcp connect failed");
  950. }
  951. }
  952. static WC_INLINE void udp_connect(SOCKET_T* sockfd, void* addr, int addrSz)
  953. {
  954. if (connect(*sockfd, (const struct sockaddr*)addr, addrSz) != 0)
  955. err_sys_with_errno("tcp connect failed");
  956. }
  957. enum {
  958. TEST_SELECT_FAIL,
  959. TEST_TIMEOUT,
  960. TEST_RECV_READY,
  961. TEST_SEND_READY,
  962. TEST_ERROR_READY
  963. };
  964. #if !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_KEIL_TCP_NET) && \
  965. !defined(WOLFSSL_TIRTOS)
  966. static WC_INLINE int tcp_select_ex(SOCKET_T socketfd, int to_sec, int rx)
  967. {
  968. fd_set fds, errfds;
  969. fd_set* recvfds = NULL;
  970. fd_set* sendfds = NULL;
  971. SOCKET_T nfds = socketfd + 1;
  972. #if !defined(__INTEGRITY)
  973. struct timeval timeout = {(to_sec > 0) ? to_sec : 0, 0};
  974. #else
  975. struct timeval timeout;
  976. #endif
  977. int result;
  978. FD_ZERO(&fds);
  979. FD_SET(socketfd, &fds);
  980. FD_ZERO(&errfds);
  981. FD_SET(socketfd, &errfds);
  982. if (rx)
  983. recvfds = &fds;
  984. else
  985. sendfds = &fds;
  986. #if defined(__INTEGRITY)
  987. timeout.tv_sec = (long long)(to_sec > 0) ? to_sec : 0, 0;
  988. #endif
  989. result = select(nfds, recvfds, sendfds, &errfds, &timeout);
  990. if (result == 0)
  991. return TEST_TIMEOUT;
  992. else if (result > 0) {
  993. if (FD_ISSET(socketfd, &fds)) {
  994. if (rx)
  995. return TEST_RECV_READY;
  996. else
  997. return TEST_SEND_READY;
  998. }
  999. else if(FD_ISSET(socketfd, &errfds))
  1000. return TEST_ERROR_READY;
  1001. }
  1002. return TEST_SELECT_FAIL;
  1003. }
  1004. static WC_INLINE int tcp_select(SOCKET_T socketfd, int to_sec)
  1005. {
  1006. return tcp_select_ex(socketfd, to_sec, 1);
  1007. }
  1008. static WC_INLINE int tcp_select_tx(SOCKET_T socketfd, int to_sec)
  1009. {
  1010. return tcp_select_ex(socketfd, to_sec, 0);
  1011. }
  1012. #elif defined(WOLFSSL_TIRTOS) || defined(WOLFSSL_KEIL_TCP_NET)
  1013. static WC_INLINE int tcp_select(SOCKET_T socketfd, int to_sec)
  1014. {
  1015. return TEST_RECV_READY;
  1016. }
  1017. static WC_INLINE int tcp_select_tx(SOCKET_T socketfd, int to_sec)
  1018. {
  1019. return TEST_SEND_READY;
  1020. }
  1021. #endif /* !WOLFSSL_MDK_ARM */
  1022. static WC_INLINE void tcp_listen(SOCKET_T* sockfd, word16* port, int useAnyAddr,
  1023. int udp, int sctp)
  1024. {
  1025. SOCKADDR_IN_T addr;
  1026. /* don't use INADDR_ANY by default, firewall may block, make user switch
  1027. on */
  1028. build_addr(&addr, (useAnyAddr ? INADDR_ANY : wolfSSLIP), *port, udp, sctp);
  1029. tcp_socket(sockfd, udp, sctp);
  1030. #if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_MDK_ARM)\
  1031. && !defined(WOLFSSL_KEIL_TCP_NET) && !defined(WOLFSSL_ZEPHYR)
  1032. {
  1033. int res, on = 1;
  1034. socklen_t len = sizeof(on);
  1035. res = setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &on, len);
  1036. if (res < 0)
  1037. err_sys_with_errno("setsockopt SO_REUSEADDR failed\n");
  1038. }
  1039. #ifdef SO_REUSEPORT
  1040. {
  1041. int res, on = 1;
  1042. socklen_t len = sizeof(on);
  1043. res = setsockopt(*sockfd, SOL_SOCKET, SO_REUSEPORT, &on, len);
  1044. if (res < 0)
  1045. err_sys_with_errno("setsockopt SO_REUSEPORT failed\n");
  1046. }
  1047. #endif
  1048. #endif
  1049. if (bind(*sockfd, (const struct sockaddr*)&addr, sizeof(addr)) != 0)
  1050. err_sys_with_errno("tcp bind failed");
  1051. if (!udp) {
  1052. #ifdef WOLFSSL_KEIL_TCP_NET
  1053. #define SOCK_LISTEN_MAX_QUEUE 1
  1054. #else
  1055. #define SOCK_LISTEN_MAX_QUEUE 5
  1056. #endif
  1057. if (listen(*sockfd, SOCK_LISTEN_MAX_QUEUE) != 0)
  1058. err_sys_with_errno("tcp listen failed");
  1059. }
  1060. #if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_TIRTOS) \
  1061. && !defined(WOLFSSL_ZEPHYR)
  1062. if (*port == 0) {
  1063. socklen_t len = sizeof(addr);
  1064. if (getsockname(*sockfd, (struct sockaddr*)&addr, &len) == 0) {
  1065. #ifndef TEST_IPV6
  1066. *port = XNTOHS(addr.sin_port);
  1067. #else
  1068. *port = XNTOHS(addr.sin6_port);
  1069. #endif
  1070. }
  1071. }
  1072. #endif
  1073. }
  1074. #if 0
  1075. static WC_INLINE int udp_read_connect(SOCKET_T sockfd)
  1076. {
  1077. SOCKADDR_IN_T cliaddr;
  1078. byte b[1500];
  1079. int n;
  1080. socklen_t len = sizeof(cliaddr);
  1081. n = (int)recvfrom(sockfd, (char*)b, sizeof(b), MSG_PEEK,
  1082. (struct sockaddr*)&cliaddr, &len);
  1083. if (n > 0) {
  1084. if (connect(sockfd, (const struct sockaddr*)&cliaddr,
  1085. sizeof(cliaddr)) != 0)
  1086. err_sys("udp connect failed");
  1087. }
  1088. else
  1089. err_sys("recvfrom failed");
  1090. return sockfd;
  1091. }
  1092. #endif
  1093. static WC_INLINE void udp_accept(SOCKET_T* sockfd, SOCKET_T* clientfd,
  1094. int useAnyAddr, word16 port, func_args* args)
  1095. {
  1096. SOCKADDR_IN_T addr;
  1097. (void)args;
  1098. build_addr(&addr, (useAnyAddr ? INADDR_ANY : wolfSSLIP), port, 1, 0);
  1099. tcp_socket(sockfd, 1, 0);
  1100. #if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_MDK_ARM) \
  1101. && !defined(WOLFSSL_KEIL_TCP_NET) && !defined(WOLFSSL_ZEPHYR)
  1102. {
  1103. int res, on = 1;
  1104. socklen_t len = sizeof(on);
  1105. res = setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &on, len);
  1106. if (res < 0)
  1107. err_sys_with_errno("setsockopt SO_REUSEADDR failed\n");
  1108. }
  1109. #ifdef SO_REUSEPORT
  1110. {
  1111. int res, on = 1;
  1112. socklen_t len = sizeof(on);
  1113. res = setsockopt(*sockfd, SOL_SOCKET, SO_REUSEPORT, &on, len);
  1114. if (res < 0)
  1115. err_sys_with_errno("setsockopt SO_REUSEPORT failed\n");
  1116. }
  1117. #endif
  1118. #endif
  1119. if (bind(*sockfd, (const struct sockaddr*)&addr, sizeof(addr)) != 0)
  1120. err_sys_with_errno("tcp bind failed");
  1121. #if (defined(NO_MAIN_DRIVER) && !defined(USE_WINDOWS_API)) && !defined(WOLFSSL_TIRTOS)
  1122. if (port == 0) {
  1123. socklen_t len = sizeof(addr);
  1124. if (getsockname(*sockfd, (struct sockaddr*)&addr, &len) == 0) {
  1125. #ifndef TEST_IPV6
  1126. port = XNTOHS(addr.sin_port);
  1127. #else
  1128. port = XNTOHS(addr.sin6_port);
  1129. #endif
  1130. }
  1131. }
  1132. #endif
  1133. #if defined(_POSIX_THREADS) && defined(NO_MAIN_DRIVER) && !defined(__MINGW32__)
  1134. /* signal ready to accept data */
  1135. {
  1136. tcp_ready* ready = args->signal;
  1137. pthread_mutex_lock(&ready->mutex);
  1138. ready->ready = 1;
  1139. ready->port = port;
  1140. pthread_cond_signal(&ready->cond);
  1141. pthread_mutex_unlock(&ready->mutex);
  1142. }
  1143. #elif defined (WOLFSSL_TIRTOS)
  1144. /* Need mutex? */
  1145. tcp_ready* ready = args->signal;
  1146. ready->ready = 1;
  1147. ready->port = port;
  1148. #else
  1149. (void)port;
  1150. #endif
  1151. *clientfd = *sockfd;
  1152. }
  1153. static WC_INLINE void tcp_accept(SOCKET_T* sockfd, SOCKET_T* clientfd,
  1154. func_args* args, word16 port, int useAnyAddr,
  1155. int udp, int sctp, int ready_file, int do_listen)
  1156. {
  1157. SOCKADDR_IN_T client_addr;
  1158. socklen_t client_len = sizeof(client_addr);
  1159. tcp_ready* ready = NULL;
  1160. (void) ready; /* Account for case when "ready" is not used */
  1161. if (udp) {
  1162. udp_accept(sockfd, clientfd, useAnyAddr, port, args);
  1163. return;
  1164. }
  1165. if(do_listen) {
  1166. tcp_listen(sockfd, &port, useAnyAddr, udp, sctp);
  1167. #if defined(_POSIX_THREADS) && defined(NO_MAIN_DRIVER) && !defined(__MINGW32__)
  1168. /* signal ready to tcp_accept */
  1169. if (args)
  1170. ready = args->signal;
  1171. if (ready) {
  1172. pthread_mutex_lock(&ready->mutex);
  1173. ready->ready = 1;
  1174. ready->port = port;
  1175. pthread_cond_signal(&ready->cond);
  1176. pthread_mutex_unlock(&ready->mutex);
  1177. }
  1178. #elif defined (WOLFSSL_TIRTOS)
  1179. /* Need mutex? */
  1180. if (args)
  1181. ready = args->signal;
  1182. if (ready) {
  1183. ready->ready = 1;
  1184. ready->port = port;
  1185. }
  1186. #endif
  1187. if (ready_file) {
  1188. #if !defined(NO_FILESYSTEM) || defined(FORCE_BUFFER_TEST)
  1189. XFILE srf = NULL;
  1190. if (args)
  1191. ready = args->signal;
  1192. if (ready) {
  1193. srf = XFOPEN(ready->srfName, "w");
  1194. if (srf) {
  1195. /* let's write port sever is listening on to ready file
  1196. external monitor can then do ephemeral ports by passing
  1197. -p 0 to server on supported platforms with -R ready_file
  1198. client can then wait for existence of ready_file and see
  1199. which port the server is listening on. */
  1200. fprintf(srf, "%d\n", (int)port);
  1201. fclose(srf);
  1202. }
  1203. }
  1204. #endif
  1205. }
  1206. }
  1207. *clientfd = accept(*sockfd, (struct sockaddr*)&client_addr,
  1208. (ACCEPT_THIRD_T)&client_len);
  1209. if(WOLFSSL_SOCKET_IS_INVALID(*clientfd)) {
  1210. err_sys_with_errno("tcp accept failed");
  1211. }
  1212. }
  1213. static WC_INLINE void tcp_set_nonblocking(SOCKET_T* sockfd)
  1214. {
  1215. #ifdef USE_WINDOWS_API
  1216. unsigned long blocking = 1;
  1217. int ret = ioctlsocket(*sockfd, FIONBIO, &blocking);
  1218. if (ret == SOCKET_ERROR)
  1219. err_sys_with_errno("ioctlsocket failed");
  1220. #elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET) \
  1221. || defined (WOLFSSL_TIRTOS)|| defined(WOLFSSL_VXWORKS) \
  1222. || defined(WOLFSSL_ZEPHYR)
  1223. /* non blocking not supported, for now */
  1224. #else
  1225. int flags = fcntl(*sockfd, F_GETFL, 0);
  1226. if (flags < 0)
  1227. err_sys_with_errno("fcntl get failed");
  1228. flags = fcntl(*sockfd, F_SETFL, flags | O_NONBLOCK);
  1229. if (flags < 0)
  1230. err_sys_with_errno("fcntl set failed");
  1231. #endif
  1232. }
  1233. #ifndef NO_PSK
  1234. /* identity is OpenSSL testing default for openssl s_client, keep same */
  1235. static const char* kIdentityStr = "Client_identity";
  1236. static WC_INLINE unsigned int my_psk_client_cb(WOLFSSL* ssl, const char* hint,
  1237. char* identity, unsigned int id_max_len, unsigned char* key,
  1238. unsigned int key_max_len)
  1239. {
  1240. (void)ssl;
  1241. (void)hint;
  1242. (void)key_max_len;
  1243. /* see internal.h MAX_PSK_ID_LEN for PSK identity limit */
  1244. XSTRNCPY(identity, kIdentityStr, id_max_len);
  1245. if (wolfSSL_GetVersion(ssl) < WOLFSSL_TLSV1_3) {
  1246. /* test key in hex is 0x1a2b3c4d , in decimal 439,041,101 , we're using
  1247. unsigned binary */
  1248. key[0] = 0x1a;
  1249. key[1] = 0x2b;
  1250. key[2] = 0x3c;
  1251. key[3] = 0x4d;
  1252. return 4; /* length of key in octets or 0 for error */
  1253. }
  1254. else {
  1255. int i;
  1256. int b = 0x01;
  1257. for (i = 0; i < 32; i++, b += 0x22) {
  1258. if (b >= 0x100)
  1259. b = 0x01;
  1260. key[i] = b;
  1261. }
  1262. return 32; /* length of key in octets or 0 for error */
  1263. }
  1264. }
  1265. static WC_INLINE unsigned int my_psk_server_cb(WOLFSSL* ssl, const char* identity,
  1266. unsigned char* key, unsigned int key_max_len)
  1267. {
  1268. (void)ssl;
  1269. (void)key_max_len;
  1270. /* see internal.h MAX_PSK_ID_LEN for PSK identity limit */
  1271. if (XSTRNCMP(identity, kIdentityStr, XSTRLEN(kIdentityStr)) != 0)
  1272. return 0;
  1273. if (wolfSSL_GetVersion(ssl) < WOLFSSL_TLSV1_3) {
  1274. /* test key in hex is 0x1a2b3c4d , in decimal 439,041,101 , we're using
  1275. unsigned binary */
  1276. key[0] = 0x1a;
  1277. key[1] = 0x2b;
  1278. key[2] = 0x3c;
  1279. key[3] = 0x4d;
  1280. return 4; /* length of key in octets or 0 for error */
  1281. }
  1282. else {
  1283. int i;
  1284. int b = 0x01;
  1285. for (i = 0; i < 32; i++, b += 0x22) {
  1286. if (b >= 0x100)
  1287. b = 0x01;
  1288. key[i] = b;
  1289. }
  1290. return 32; /* length of key in octets or 0 for error */
  1291. }
  1292. }
  1293. static WC_INLINE unsigned int my_psk_client_tls13_cb(WOLFSSL* ssl,
  1294. const char* hint, char* identity, unsigned int id_max_len,
  1295. unsigned char* key, unsigned int key_max_len, const char** ciphersuite)
  1296. {
  1297. int i;
  1298. int b = 0x01;
  1299. const char* userCipher = (const char*)wolfSSL_get_psk_callback_ctx(ssl);
  1300. (void)ssl;
  1301. (void)hint;
  1302. (void)key_max_len;
  1303. /* see internal.h MAX_PSK_ID_LEN for PSK identity limit */
  1304. XSTRNCPY(identity, kIdentityStr, id_max_len);
  1305. for (i = 0; i < 32; i++, b += 0x22) {
  1306. if (b >= 0x100)
  1307. b = 0x01;
  1308. key[i] = b;
  1309. }
  1310. *ciphersuite = userCipher ? userCipher : "TLS13-AES128-GCM-SHA256";
  1311. return 32; /* length of key in octets or 0 for error */
  1312. }
  1313. static WC_INLINE unsigned int my_psk_server_tls13_cb(WOLFSSL* ssl,
  1314. const char* identity, unsigned char* key, unsigned int key_max_len,
  1315. const char** ciphersuite)
  1316. {
  1317. int i;
  1318. int b = 0x01;
  1319. const char* userCipher = (const char*)wolfSSL_get_psk_callback_ctx(ssl);
  1320. (void)ssl;
  1321. (void)key_max_len;
  1322. /* see internal.h MAX_PSK_ID_LEN for PSK identity limit */
  1323. if (XSTRNCMP(identity, kIdentityStr, XSTRLEN(kIdentityStr)) != 0)
  1324. return 0;
  1325. for (i = 0; i < 32; i++, b += 0x22) {
  1326. if (b >= 0x100)
  1327. b = 0x01;
  1328. key[i] = b;
  1329. }
  1330. *ciphersuite = userCipher ? userCipher : "TLS13-AES128-GCM-SHA256";
  1331. return 32; /* length of key in octets or 0 for error */
  1332. }
  1333. #endif /* !NO_PSK */
  1334. #if defined(WOLFSSL_USER_CURRTIME)
  1335. extern double current_time(int reset);
  1336. #elif defined(USE_WINDOWS_API)
  1337. #define WIN32_LEAN_AND_MEAN
  1338. #include <windows.h>
  1339. static WC_INLINE double current_time(int reset)
  1340. {
  1341. static int init = 0;
  1342. static LARGE_INTEGER freq;
  1343. LARGE_INTEGER count;
  1344. if (!init) {
  1345. QueryPerformanceFrequency(&freq);
  1346. init = 1;
  1347. }
  1348. QueryPerformanceCounter(&count);
  1349. (void)reset;
  1350. return (double)count.QuadPart / freq.QuadPart;
  1351. }
  1352. #elif defined(WOLFSSL_TIRTOS)
  1353. extern double current_time();
  1354. #elif defined(WOLFSSL_ZEPHYR)
  1355. extern double current_time();
  1356. #else
  1357. #if !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_KEIL_TCP_NET) && !defined(WOLFSSL_CHIBIOS)
  1358. #include <sys/time.h>
  1359. static WC_INLINE double current_time(int reset)
  1360. {
  1361. struct timeval tv;
  1362. gettimeofday(&tv, 0);
  1363. (void)reset;
  1364. return (double)tv.tv_sec + (double)tv.tv_usec / 1000000;
  1365. }
  1366. #else
  1367. extern double current_time(int reset);
  1368. #endif
  1369. #endif /* USE_WINDOWS_API */
  1370. #if defined(HAVE_OCSP) && defined(WOLFSSL_NONBLOCK_OCSP)
  1371. static WC_INLINE int OCSPIOCb(void* ioCtx, const char* url, int urlSz,
  1372. unsigned char* request, int requestSz, unsigned char** response)
  1373. {
  1374. #ifdef TEST_NONBLOCK_CERTS
  1375. static int ioCbCnt = 0;
  1376. #endif
  1377. (void)ioCtx;
  1378. (void)url;
  1379. (void)urlSz;
  1380. (void)request;
  1381. (void)requestSz;
  1382. (void)response;
  1383. #ifdef TEST_NONBLOCK_CERTS
  1384. if (ioCbCnt) {
  1385. ioCbCnt = 0;
  1386. return EmbedOcspLookup(ioCtx, url, urlSz, request, requestSz, response);
  1387. }
  1388. else {
  1389. ioCbCnt = 1;
  1390. return WOLFSSL_CBIO_ERR_WANT_READ;
  1391. }
  1392. #else
  1393. return EmbedOcspLookup(ioCtx, url, urlSz, request, requestSz, response);
  1394. #endif
  1395. }
  1396. static WC_INLINE void OCSPRespFreeCb(void* ioCtx, unsigned char* response)
  1397. {
  1398. return EmbedOcspRespFree(ioCtx, response);
  1399. }
  1400. #endif
  1401. #if !defined(NO_CERTS)
  1402. #if !defined(NO_FILESYSTEM) || \
  1403. (defined(NO_FILESYSTEM) && defined(FORCE_BUFFER_TEST))
  1404. /* reads file size, allocates buffer, reads into buffer, returns buffer */
  1405. static WC_INLINE int load_file(const char* fname, byte** buf, size_t* bufLen)
  1406. {
  1407. int ret;
  1408. long int fileSz;
  1409. XFILE lFile;
  1410. if (fname == NULL || buf == NULL || bufLen == NULL)
  1411. return BAD_FUNC_ARG;
  1412. /* set defaults */
  1413. *buf = NULL;
  1414. *bufLen = 0;
  1415. /* open file (read-only binary) */
  1416. lFile = XFOPEN(fname, "rb");
  1417. if (!lFile) {
  1418. printf("Error loading %s\n", fname);
  1419. return BAD_PATH_ERROR;
  1420. }
  1421. fseek(lFile, 0, SEEK_END);
  1422. fileSz = (int)ftell(lFile);
  1423. rewind(lFile);
  1424. if (fileSz > 0) {
  1425. *bufLen = (size_t)fileSz;
  1426. *buf = (byte*)malloc(*bufLen);
  1427. if (*buf == NULL) {
  1428. ret = MEMORY_E;
  1429. printf("Error allocating %lu bytes\n", (unsigned long)*bufLen);
  1430. }
  1431. else {
  1432. size_t readLen = fread(*buf, *bufLen, 1, lFile);
  1433. /* check response code */
  1434. ret = (readLen > 0) ? 0 : -1;
  1435. }
  1436. }
  1437. else {
  1438. ret = BUFFER_E;
  1439. }
  1440. fclose(lFile);
  1441. return ret;
  1442. }
  1443. enum {
  1444. WOLFSSL_CA = 1,
  1445. WOLFSSL_CERT = 2,
  1446. WOLFSSL_KEY = 3,
  1447. WOLFSSL_CERT_CHAIN = 4,
  1448. };
  1449. static WC_INLINE void load_buffer(WOLFSSL_CTX* ctx, const char* fname, int type)
  1450. {
  1451. int format = WOLFSSL_FILETYPE_PEM;
  1452. byte* buff = NULL;
  1453. size_t sz = 0;
  1454. if (load_file(fname, &buff, &sz) != 0) {
  1455. err_sys("can't open file for buffer load "
  1456. "Please run from wolfSSL home directory if not");
  1457. }
  1458. /* determine format */
  1459. if (strstr(fname, ".der"))
  1460. format = WOLFSSL_FILETYPE_ASN1;
  1461. if (type == WOLFSSL_CA) {
  1462. if (wolfSSL_CTX_load_verify_buffer(ctx, buff, (long)sz, format)
  1463. != WOLFSSL_SUCCESS)
  1464. err_sys("can't load buffer ca file");
  1465. }
  1466. else if (type == WOLFSSL_CERT) {
  1467. if (wolfSSL_CTX_use_certificate_buffer(ctx, buff, (long)sz,
  1468. format) != WOLFSSL_SUCCESS)
  1469. err_sys("can't load buffer cert file");
  1470. }
  1471. else if (type == WOLFSSL_KEY) {
  1472. if (wolfSSL_CTX_use_PrivateKey_buffer(ctx, buff, (long)sz,
  1473. format) != WOLFSSL_SUCCESS)
  1474. err_sys("can't load buffer key file");
  1475. }
  1476. else if (type == WOLFSSL_CERT_CHAIN) {
  1477. if (wolfSSL_CTX_use_certificate_chain_buffer_format(ctx, buff,
  1478. (long)sz, format) != WOLFSSL_SUCCESS)
  1479. err_sys("can't load cert chain buffer");
  1480. }
  1481. if (buff)
  1482. free(buff);
  1483. }
  1484. static WC_INLINE void load_ssl_buffer(WOLFSSL* ssl, const char* fname, int type)
  1485. {
  1486. int format = WOLFSSL_FILETYPE_PEM;
  1487. byte* buff = NULL;
  1488. size_t sz = 0;
  1489. if (load_file(fname, &buff, &sz) != 0) {
  1490. err_sys("can't open file for buffer load "
  1491. "Please run from wolfSSL home directory if not");
  1492. }
  1493. /* determine format */
  1494. if (strstr(fname, ".der"))
  1495. format = WOLFSSL_FILETYPE_ASN1;
  1496. if (type == WOLFSSL_CA) {
  1497. /* verify certs (CA's) use the shared ctx->cm (WOLFSSL_CERT_MANAGER) */
  1498. WOLFSSL_CTX* ctx = wolfSSL_get_SSL_CTX(ssl);
  1499. if (wolfSSL_CTX_load_verify_buffer(ctx, buff, (long)sz, format)
  1500. != WOLFSSL_SUCCESS)
  1501. err_sys("can't load buffer ca file");
  1502. }
  1503. else if (type == WOLFSSL_CERT) {
  1504. if (wolfSSL_use_certificate_buffer(ssl, buff, (long)sz,
  1505. format) != WOLFSSL_SUCCESS)
  1506. err_sys("can't load buffer cert file");
  1507. }
  1508. else if (type == WOLFSSL_KEY) {
  1509. if (wolfSSL_use_PrivateKey_buffer(ssl, buff, (long)sz,
  1510. format) != WOLFSSL_SUCCESS)
  1511. err_sys("can't load buffer key file");
  1512. }
  1513. else if (type == WOLFSSL_CERT_CHAIN) {
  1514. if (wolfSSL_use_certificate_chain_buffer_format(ssl, buff,
  1515. (long)sz, format) != WOLFSSL_SUCCESS)
  1516. err_sys("can't load cert chain buffer");
  1517. }
  1518. if (buff)
  1519. free(buff);
  1520. }
  1521. #ifdef TEST_PK_PRIVKEY
  1522. static WC_INLINE int load_key_file(const char* fname, byte** derBuf, word32* derLen)
  1523. {
  1524. int ret;
  1525. byte* buf = NULL;
  1526. size_t bufLen;
  1527. ret = load_file(fname, &buf, &bufLen);
  1528. if (ret != 0)
  1529. return ret;
  1530. *derBuf = (byte*)malloc(bufLen);
  1531. if (*derBuf == NULL) {
  1532. free(buf);
  1533. return MEMORY_E;
  1534. }
  1535. ret = wc_KeyPemToDer(buf, (word32)bufLen, *derBuf, (word32)bufLen, NULL);
  1536. if (ret < 0) {
  1537. free(buf);
  1538. free(*derBuf);
  1539. return ret;
  1540. }
  1541. *derLen = ret;
  1542. free(buf);
  1543. return 0;
  1544. }
  1545. #endif /* TEST_PK_PRIVKEY */
  1546. #endif /* !NO_FILESYSTEM || (NO_FILESYSTEM && FORCE_BUFFER_TEST) */
  1547. #endif /* !NO_CERTS */
  1548. enum {
  1549. VERIFY_OVERRIDE_ERROR,
  1550. VERIFY_FORCE_FAIL,
  1551. VERIFY_USE_PREVERFIY,
  1552. VERIFY_OVERRIDE_DATE_ERR,
  1553. };
  1554. static THREAD_LS_T int myVerifyAction = VERIFY_OVERRIDE_ERROR;
  1555. /* The verify callback is called for every certificate only when
  1556. * --enable-opensslextra is defined because it sets WOLFSSL_ALWAYS_VERIFY_CB and
  1557. * WOLFSSL_VERIFY_CB_ALL_CERTS.
  1558. * Normal cases of the verify callback only occur on certificate failures when the
  1559. * wolfSSL_set_verify(ssl, SSL_VERIFY_PEER, myVerifyCb); is called
  1560. */
  1561. static WC_INLINE int myVerify(int preverify, WOLFSSL_X509_STORE_CTX* store)
  1562. {
  1563. char buffer[WOLFSSL_MAX_ERROR_SZ];
  1564. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  1565. WOLFSSL_X509* peer;
  1566. #if defined(SHOW_CERTS) && !defined(NO_FILESYSTEM)
  1567. WOLFSSL_BIO* bio = NULL;
  1568. WOLFSSL_STACK* sk = NULL;
  1569. X509* x509 = NULL;
  1570. int i = 0;
  1571. #endif
  1572. #endif
  1573. (void)preverify;
  1574. /* Verify Callback Arguments:
  1575. * preverify: 1=Verify Okay, 0=Failure
  1576. * store->error: Failure error code (0 indicates no failure)
  1577. * store->current_cert: Current WOLFSSL_X509 object (only with OPENSSL_EXTRA)
  1578. * store->error_depth: Current Index
  1579. * store->domain: Subject CN as string (null term)
  1580. * store->totalCerts: Number of certs presented by peer
  1581. * store->certs[i]: A `WOLFSSL_BUFFER_INFO` with plain DER for each cert
  1582. * store->store: WOLFSSL_X509_STORE with CA cert chain
  1583. * store->store->cm: WOLFSSL_CERT_MANAGER
  1584. * store->ex_data: The WOLFSSL object pointer
  1585. * store->discardSessionCerts: When set to non-zero value session certs
  1586. will be discarded (only with SESSION_CERTS)
  1587. */
  1588. printf("In verification callback, error = %d, %s\n", store->error,
  1589. wolfSSL_ERR_error_string(store->error, buffer));
  1590. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  1591. peer = store->current_cert;
  1592. if (peer) {
  1593. char* issuer = wolfSSL_X509_NAME_oneline(
  1594. wolfSSL_X509_get_issuer_name(peer), 0, 0);
  1595. char* subject = wolfSSL_X509_NAME_oneline(
  1596. wolfSSL_X509_get_subject_name(peer), 0, 0);
  1597. printf("\tPeer's cert info:\n issuer : %s\n subject: %s\n", issuer,
  1598. subject);
  1599. XFREE(subject, 0, DYNAMIC_TYPE_OPENSSL);
  1600. XFREE(issuer, 0, DYNAMIC_TYPE_OPENSSL);
  1601. #if defined(SHOW_CERTS) && !defined(NO_FILESYSTEM)
  1602. /* avoid printing duplicate certs */
  1603. if (store->depth == 1) {
  1604. /* retrieve x509 certs and display them on stdout */
  1605. sk = wolfSSL_X509_STORE_GetCerts(store);
  1606. for (i = 0; i < wolfSSL_sk_X509_num(sk); i++) {
  1607. x509 = wolfSSL_sk_X509_value(sk, i);
  1608. bio = wolfSSL_BIO_new(wolfSSL_BIO_s_file());
  1609. if (bio != NULL) {
  1610. wolfSSL_BIO_set_fp(bio, stdout, BIO_NOCLOSE);
  1611. wolfSSL_X509_print(bio, x509);
  1612. wolfSSL_BIO_free(bio);
  1613. }
  1614. }
  1615. wolfSSL_sk_X509_free(sk);
  1616. }
  1617. #endif
  1618. }
  1619. else
  1620. printf("\tPeer has no cert!\n");
  1621. #else
  1622. printf("\tPeer certs: %d\n", store->totalCerts);
  1623. #ifdef SHOW_CERTS
  1624. { int i;
  1625. for (i=0; i<store->totalCerts; i++) {
  1626. WOLFSSL_BUFFER_INFO* cert = &store->certs[i];
  1627. printf("\t\tCert %d: Ptr %p, Len %u\n", i, cert->buffer, cert->length);
  1628. }
  1629. }
  1630. #endif /* SHOW_CERTS */
  1631. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  1632. printf("\tSubject's domain name at %d is %s\n", store->error_depth, store->domain);
  1633. /* Testing forced fail case by return zero */
  1634. if (myVerifyAction == VERIFY_FORCE_FAIL) {
  1635. return 0; /* test failure case */
  1636. }
  1637. if (myVerifyAction == VERIFY_OVERRIDE_DATE_ERR &&
  1638. (store->error == ASN_BEFORE_DATE_E || store->error == ASN_AFTER_DATE_E)) {
  1639. printf("Overriding cert date error as example for bad clock testing\n");
  1640. return 1;
  1641. }
  1642. /* If error indicate we are overriding it for testing purposes */
  1643. if (store->error != 0 && myVerifyAction == VERIFY_OVERRIDE_ERROR) {
  1644. printf("\tAllowing failed certificate check, testing only "
  1645. "(shouldn't do this in production)\n");
  1646. }
  1647. /* A non-zero return code indicates failure override */
  1648. return (myVerifyAction == VERIFY_OVERRIDE_ERROR) ? 1 : preverify;
  1649. }
  1650. #ifdef HAVE_EXT_CACHE
  1651. static WC_INLINE WOLFSSL_SESSION* mySessGetCb(WOLFSSL* ssl, unsigned char* id,
  1652. int id_len, int* copy)
  1653. {
  1654. (void)ssl;
  1655. (void)id;
  1656. (void)id_len;
  1657. (void)copy;
  1658. /* using internal cache, this is for testing only */
  1659. return NULL;
  1660. }
  1661. static WC_INLINE int mySessNewCb(WOLFSSL* ssl, WOLFSSL_SESSION* session)
  1662. {
  1663. (void)ssl;
  1664. (void)session;
  1665. /* using internal cache, this is for testing only */
  1666. return 0;
  1667. }
  1668. static WC_INLINE void mySessRemCb(WOLFSSL_CTX* ctx, WOLFSSL_SESSION* session)
  1669. {
  1670. (void)ctx;
  1671. (void)session;
  1672. /* using internal cache, this is for testing only */
  1673. }
  1674. #endif /* HAVE_EXT_CACHE */
  1675. #ifdef HAVE_CRL
  1676. static WC_INLINE void CRL_CallBack(const char* url)
  1677. {
  1678. printf("CRL callback url = %s\n", url);
  1679. }
  1680. #endif
  1681. #ifndef NO_DH
  1682. static WC_INLINE void SetDH(WOLFSSL* ssl)
  1683. {
  1684. /* dh1024 p */
  1685. static const unsigned char p[] =
  1686. {
  1687. 0xE6, 0x96, 0x9D, 0x3D, 0x49, 0x5B, 0xE3, 0x2C, 0x7C, 0xF1, 0x80, 0xC3,
  1688. 0xBD, 0xD4, 0x79, 0x8E, 0x91, 0xB7, 0x81, 0x82, 0x51, 0xBB, 0x05, 0x5E,
  1689. 0x2A, 0x20, 0x64, 0x90, 0x4A, 0x79, 0xA7, 0x70, 0xFA, 0x15, 0xA2, 0x59,
  1690. 0xCB, 0xD5, 0x23, 0xA6, 0xA6, 0xEF, 0x09, 0xC4, 0x30, 0x48, 0xD5, 0xA2,
  1691. 0x2F, 0x97, 0x1F, 0x3C, 0x20, 0x12, 0x9B, 0x48, 0x00, 0x0E, 0x6E, 0xDD,
  1692. 0x06, 0x1C, 0xBC, 0x05, 0x3E, 0x37, 0x1D, 0x79, 0x4E, 0x53, 0x27, 0xDF,
  1693. 0x61, 0x1E, 0xBB, 0xBE, 0x1B, 0xAC, 0x9B, 0x5C, 0x60, 0x44, 0xCF, 0x02,
  1694. 0x3D, 0x76, 0xE0, 0x5E, 0xEA, 0x9B, 0xAD, 0x99, 0x1B, 0x13, 0xA6, 0x3C,
  1695. 0x97, 0x4E, 0x9E, 0xF1, 0x83, 0x9E, 0xB5, 0xDB, 0x12, 0x51, 0x36, 0xF7,
  1696. 0x26, 0x2E, 0x56, 0xA8, 0x87, 0x15, 0x38, 0xDF, 0xD8, 0x23, 0xC6, 0x50,
  1697. 0x50, 0x85, 0xE2, 0x1F, 0x0D, 0xD5, 0xC8, 0x6B,
  1698. };
  1699. /* dh1024 g */
  1700. static const unsigned char g[] =
  1701. {
  1702. 0x02,
  1703. };
  1704. wolfSSL_SetTmpDH(ssl, p, sizeof(p), g, sizeof(g));
  1705. }
  1706. static WC_INLINE void SetDHCtx(WOLFSSL_CTX* ctx)
  1707. {
  1708. /* dh1024 p */
  1709. static const unsigned char p[] =
  1710. {
  1711. 0xE6, 0x96, 0x9D, 0x3D, 0x49, 0x5B, 0xE3, 0x2C, 0x7C, 0xF1, 0x80, 0xC3,
  1712. 0xBD, 0xD4, 0x79, 0x8E, 0x91, 0xB7, 0x81, 0x82, 0x51, 0xBB, 0x05, 0x5E,
  1713. 0x2A, 0x20, 0x64, 0x90, 0x4A, 0x79, 0xA7, 0x70, 0xFA, 0x15, 0xA2, 0x59,
  1714. 0xCB, 0xD5, 0x23, 0xA6, 0xA6, 0xEF, 0x09, 0xC4, 0x30, 0x48, 0xD5, 0xA2,
  1715. 0x2F, 0x97, 0x1F, 0x3C, 0x20, 0x12, 0x9B, 0x48, 0x00, 0x0E, 0x6E, 0xDD,
  1716. 0x06, 0x1C, 0xBC, 0x05, 0x3E, 0x37, 0x1D, 0x79, 0x4E, 0x53, 0x27, 0xDF,
  1717. 0x61, 0x1E, 0xBB, 0xBE, 0x1B, 0xAC, 0x9B, 0x5C, 0x60, 0x44, 0xCF, 0x02,
  1718. 0x3D, 0x76, 0xE0, 0x5E, 0xEA, 0x9B, 0xAD, 0x99, 0x1B, 0x13, 0xA6, 0x3C,
  1719. 0x97, 0x4E, 0x9E, 0xF1, 0x83, 0x9E, 0xB5, 0xDB, 0x12, 0x51, 0x36, 0xF7,
  1720. 0x26, 0x2E, 0x56, 0xA8, 0x87, 0x15, 0x38, 0xDF, 0xD8, 0x23, 0xC6, 0x50,
  1721. 0x50, 0x85, 0xE2, 0x1F, 0x0D, 0xD5, 0xC8, 0x6B,
  1722. };
  1723. /* dh1024 g */
  1724. static const unsigned char g[] =
  1725. {
  1726. 0x02,
  1727. };
  1728. wolfSSL_CTX_SetTmpDH(ctx, p, sizeof(p), g, sizeof(g));
  1729. }
  1730. #endif /* NO_DH */
  1731. #ifndef NO_CERTS
  1732. static WC_INLINE void CaCb(unsigned char* der, int sz, int type)
  1733. {
  1734. (void)der;
  1735. printf("Got CA cache add callback, derSz = %d, type = %d\n", sz, type);
  1736. }
  1737. #endif /* !NO_CERTS */
  1738. /* Wolf Root Directory Helper */
  1739. /* KEIL-RL File System does not support relative directory */
  1740. #if !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_KEIL_FS) && !defined(WOLFSSL_TIRTOS)
  1741. /* Maximum depth to search for WolfSSL root */
  1742. #define MAX_WOLF_ROOT_DEPTH 5
  1743. static WC_INLINE int ChangeToWolfRoot(void)
  1744. {
  1745. #if !defined(NO_FILESYSTEM) || defined(FORCE_BUFFER_TEST)
  1746. int depth, res;
  1747. XFILE keyFile;
  1748. for(depth = 0; depth <= MAX_WOLF_ROOT_DEPTH; depth++) {
  1749. keyFile = XFOPEN(ntruKeyFile, "rb");
  1750. if (keyFile != NULL) {
  1751. fclose(keyFile);
  1752. return depth;
  1753. }
  1754. #ifdef USE_WINDOWS_API
  1755. res = SetCurrentDirectoryA("..\\");
  1756. #else
  1757. res = chdir("../");
  1758. #endif
  1759. if (res < 0) {
  1760. printf("chdir to ../ failed!\n");
  1761. break;
  1762. }
  1763. }
  1764. err_sys("wolf root not found");
  1765. return -1;
  1766. #else
  1767. return 0;
  1768. #endif
  1769. }
  1770. #endif /* !defined(WOLFSSL_MDK_ARM) && !defined(WOLFSSL_KEIL_FS) && !defined(WOLFSSL_TIRTOS) */
  1771. #ifdef HAVE_STACK_SIZE
  1772. typedef THREAD_RETURN WOLFSSL_THREAD (*thread_func)(void* args);
  1773. #define STACK_CHECK_VAL 0x01
  1774. struct stack_size_debug_context {
  1775. unsigned char *myStack;
  1776. size_t stackSize;
  1777. #ifdef HAVE_STACK_SIZE_VERBOSE
  1778. size_t *stackSizeHWM_ptr;
  1779. thread_func fn;
  1780. void *args;
  1781. #endif
  1782. };
  1783. #ifdef HAVE_STACK_SIZE_VERBOSE
  1784. /* per-subtest stack high water mark tracking.
  1785. *
  1786. * enable with
  1787. *
  1788. * ./configure --enable-stacksize=verbose [...]
  1789. */
  1790. static THREAD_RETURN debug_stack_size_verbose_shim(struct stack_size_debug_context *shim_args) {
  1791. StackSizeCheck_myStack = shim_args->myStack;
  1792. StackSizeCheck_stackSize = shim_args->stackSize;
  1793. StackSizeCheck_stackSizeHWM_ptr = shim_args->stackSizeHWM_ptr;
  1794. return shim_args->fn(shim_args->args);
  1795. }
  1796. static WC_INLINE int StackSizeSetOffset(const char *funcname, void *p)
  1797. {
  1798. if (StackSizeCheck_myStack == NULL)
  1799. return -BAD_FUNC_ARG;
  1800. StackSizeCheck_stackOffsetPointer = p;
  1801. printf("setting stack relative offset reference mark in %s to +%lu\n",
  1802. funcname, (unsigned long)((char*)(StackSizeCheck_myStack +
  1803. StackSizeCheck_stackSize) - (char *)p));
  1804. return 0;
  1805. }
  1806. static WC_INLINE ssize_t StackSizeHWM(void)
  1807. {
  1808. size_t i;
  1809. ssize_t used;
  1810. if (StackSizeCheck_myStack == NULL)
  1811. return -BAD_FUNC_ARG;
  1812. for (i = 0; i < StackSizeCheck_stackSize; i++) {
  1813. if (StackSizeCheck_myStack[i] != STACK_CHECK_VAL) {
  1814. break;
  1815. }
  1816. }
  1817. used = StackSizeCheck_stackSize - i;
  1818. if ((ssize_t)*StackSizeCheck_stackSizeHWM_ptr < used)
  1819. *StackSizeCheck_stackSizeHWM_ptr = used;
  1820. return used;
  1821. }
  1822. static WC_INLINE ssize_t StackSizeHWM_OffsetCorrected(void)
  1823. {
  1824. ssize_t used = StackSizeHWM();
  1825. if (used < 0)
  1826. return used;
  1827. if (StackSizeCheck_stackOffsetPointer)
  1828. used -= (ssize_t)(((char *)StackSizeCheck_myStack + StackSizeCheck_stackSize) - (char *)StackSizeCheck_stackOffsetPointer);
  1829. return used;
  1830. }
  1831. static
  1832. #ifdef __GNUC__
  1833. __attribute__((unused)) __attribute__((noinline))
  1834. #endif
  1835. int StackSizeHWMReset(void)
  1836. {
  1837. volatile ssize_t i;
  1838. if (StackSizeCheck_myStack == NULL)
  1839. return -BAD_FUNC_ARG;
  1840. for (i = (ssize_t)((char *)&i - (char *)StackSizeCheck_myStack) - (ssize_t)sizeof i - 1; i >= 0; --i)
  1841. {
  1842. StackSizeCheck_myStack[i] = STACK_CHECK_VAL;
  1843. }
  1844. return 0;
  1845. }
  1846. #define STACK_SIZE_CHECKPOINT(...) ({ \
  1847. ssize_t HWM = StackSizeHWM_OffsetCorrected(); \
  1848. __VA_ARGS__; \
  1849. printf(" relative stack peak usage = %ld bytes\n", HWM); \
  1850. StackSizeHWMReset(); \
  1851. })
  1852. #define STACK_SIZE_CHECKPOINT_WITH_MAX_CHECK(max, ...) ({ \
  1853. ssize_t HWM = StackSizeHWM_OffsetCorrected(); \
  1854. int _ret; \
  1855. __VA_ARGS__; \
  1856. printf(" relative stack peak usage = %ld bytes\n", HWM); \
  1857. _ret = StackSizeHWMReset(); \
  1858. if ((max >= 0) && (HWM > (ssize_t)(max))) { \
  1859. printf(" relative stack usage at %s L%d exceeds designated max %ld bytes.\n", __FILE__, __LINE__, (ssize_t)(max)); \
  1860. _ret = -1; \
  1861. } \
  1862. _ret; \
  1863. })
  1864. #ifdef __GNUC__
  1865. #define STACK_SIZE_INIT() (void)StackSizeSetOffset(__FUNCTION__, __builtin_frame_address(0))
  1866. #endif
  1867. #endif /* HAVE_STACK_SIZE_VERBOSE */
  1868. static WC_INLINE int StackSizeCheck(func_args* args, thread_func tf)
  1869. {
  1870. size_t i;
  1871. int ret;
  1872. void* status;
  1873. unsigned char* myStack = NULL;
  1874. size_t stackSize = 1024*1024;
  1875. pthread_attr_t myAttr;
  1876. pthread_t threadId;
  1877. #ifdef HAVE_STACK_SIZE_VERBOSE
  1878. struct stack_size_debug_context shim_args;
  1879. #endif
  1880. #ifdef PTHREAD_STACK_MIN
  1881. if (stackSize < PTHREAD_STACK_MIN)
  1882. stackSize = PTHREAD_STACK_MIN;
  1883. #endif
  1884. ret = posix_memalign((void**)&myStack, sysconf(_SC_PAGESIZE), stackSize);
  1885. if (ret != 0 || myStack == NULL)
  1886. err_sys_with_errno("posix_memalign failed\n");
  1887. XMEMSET(myStack, STACK_CHECK_VAL, stackSize);
  1888. ret = pthread_attr_init(&myAttr);
  1889. if (ret != 0)
  1890. err_sys("attr_init failed");
  1891. ret = pthread_attr_setstack(&myAttr, myStack, stackSize);
  1892. if (ret != 0)
  1893. err_sys("attr_setstackaddr failed");
  1894. #ifdef HAVE_STACK_SIZE_VERBOSE
  1895. StackSizeCheck_stackSizeHWM = 0;
  1896. shim_args.myStack = myStack;
  1897. shim_args.stackSize = stackSize;
  1898. shim_args.stackSizeHWM_ptr = &StackSizeCheck_stackSizeHWM;
  1899. shim_args.fn = tf;
  1900. shim_args.args = args;
  1901. ret = pthread_create(&threadId, &myAttr, (thread_func)debug_stack_size_verbose_shim, (void *)&shim_args);
  1902. #else
  1903. ret = pthread_create(&threadId, &myAttr, tf, args);
  1904. #endif
  1905. if (ret != 0) {
  1906. perror("pthread_create failed");
  1907. exit(EXIT_FAILURE);
  1908. }
  1909. ret = pthread_join(threadId, &status);
  1910. if (ret != 0)
  1911. err_sys("pthread_join failed");
  1912. for (i = 0; i < stackSize; i++) {
  1913. if (myStack[i] != STACK_CHECK_VAL) {
  1914. break;
  1915. }
  1916. }
  1917. free(myStack);
  1918. #ifdef HAVE_STACK_SIZE_VERBOSE
  1919. printf("stack used = %lu\n", StackSizeCheck_stackSizeHWM > (stackSize - i)
  1920. ? (unsigned long)StackSizeCheck_stackSizeHWM
  1921. : (unsigned long)(stackSize - i));
  1922. #else
  1923. {
  1924. size_t used = stackSize - i;
  1925. printf("stack used = %lu\n", (unsigned long)used);
  1926. }
  1927. #endif
  1928. return (int)((size_t)status);
  1929. }
  1930. static WC_INLINE int StackSizeCheck_launch(func_args* args, thread_func tf, pthread_t *threadId, void **stack_context)
  1931. {
  1932. int ret;
  1933. unsigned char* myStack = NULL;
  1934. size_t stackSize = 1024*1024;
  1935. pthread_attr_t myAttr;
  1936. #ifdef PTHREAD_STACK_MIN
  1937. if (stackSize < PTHREAD_STACK_MIN)
  1938. stackSize = PTHREAD_STACK_MIN;
  1939. #endif
  1940. struct stack_size_debug_context *shim_args = (struct stack_size_debug_context *)malloc(sizeof *shim_args);
  1941. if (! shim_args) {
  1942. perror("malloc");
  1943. exit(EXIT_FAILURE);
  1944. }
  1945. ret = posix_memalign((void**)&myStack, sysconf(_SC_PAGESIZE), stackSize);
  1946. if (ret != 0 || myStack == NULL)
  1947. err_sys_with_errno("posix_memalign failed\n");
  1948. XMEMSET(myStack, STACK_CHECK_VAL, stackSize);
  1949. ret = pthread_attr_init(&myAttr);
  1950. if (ret != 0)
  1951. err_sys("attr_init failed");
  1952. ret = pthread_attr_setstack(&myAttr, myStack, stackSize);
  1953. if (ret != 0)
  1954. err_sys("attr_setstackaddr failed");
  1955. shim_args->myStack = myStack;
  1956. shim_args->stackSize = stackSize;
  1957. #ifdef HAVE_STACK_SIZE_VERBOSE
  1958. shim_args->stackSizeHWM_ptr = &StackSizeCheck_stackSizeHWM;
  1959. shim_args->fn = tf;
  1960. shim_args->args = args;
  1961. ret = pthread_create(threadId, &myAttr, (thread_func)debug_stack_size_verbose_shim, (void *)shim_args);
  1962. #else
  1963. ret = pthread_create(threadId, &myAttr, tf, args);
  1964. #endif
  1965. if (ret != 0) {
  1966. fprintf(stderr,"pthread_create failed: %s",strerror(ret));
  1967. exit(EXIT_FAILURE);
  1968. }
  1969. *stack_context = (void *)shim_args;
  1970. return 0;
  1971. }
  1972. static WC_INLINE int StackSizeCheck_reap(pthread_t threadId, void *stack_context)
  1973. {
  1974. struct stack_size_debug_context *shim_args = (struct stack_size_debug_context *)stack_context;
  1975. size_t i;
  1976. void *status;
  1977. int ret = pthread_join(threadId, &status);
  1978. if (ret != 0)
  1979. err_sys("pthread_join failed");
  1980. for (i = 0; i < shim_args->stackSize; i++) {
  1981. if (shim_args->myStack[i] != STACK_CHECK_VAL) {
  1982. break;
  1983. }
  1984. }
  1985. free(shim_args->myStack);
  1986. #ifdef HAVE_STACK_SIZE_VERBOSE
  1987. printf("stack used = %lu\n",
  1988. *shim_args->stackSizeHWM_ptr > (shim_args->stackSize - i)
  1989. ? (unsigned long)*shim_args->stackSizeHWM_ptr
  1990. : (unsigned long)(shim_args->stackSize - i));
  1991. #else
  1992. {
  1993. size_t used = shim_args->stackSize - i;
  1994. printf("stack used = %lu\n", (unsigned long)used);
  1995. }
  1996. #endif
  1997. free(shim_args);
  1998. return (int)((size_t)status);
  1999. }
  2000. #endif /* HAVE_STACK_SIZE */
  2001. #ifndef STACK_SIZE_CHECKPOINT
  2002. #define STACK_SIZE_CHECKPOINT(...) (__VA_ARGS__)
  2003. #endif
  2004. #ifndef STACK_SIZE_INIT
  2005. #define STACK_SIZE_INIT()
  2006. #endif
  2007. #ifdef STACK_TRAP
  2008. /* good settings
  2009. --enable-debug --disable-shared C_EXTRA_FLAGS="-DUSER_TIME -DTFM_TIMING_RESISTANT -DPOSITIVE_EXP_ONLY -DSTACK_TRAP"
  2010. */
  2011. #ifdef HAVE_STACK_SIZE
  2012. /* client only for now, setrlimit will fail if pthread_create() called */
  2013. /* STACK_SIZE does pthread_create() on client */
  2014. #error "can't use STACK_TRAP with STACK_SIZE, setrlimit will fail"
  2015. #endif /* HAVE_STACK_SIZE */
  2016. static WC_INLINE void StackTrap(void)
  2017. {
  2018. struct rlimit rl;
  2019. if (getrlimit(RLIMIT_STACK, &rl) != 0)
  2020. err_sys_with_errno("getrlimit failed");
  2021. printf("rlim_cur = %llu\n", rl.rlim_cur);
  2022. rl.rlim_cur = 1024*21; /* adjust trap size here */
  2023. if (setrlimit(RLIMIT_STACK, &rl) != 0)
  2024. err_sys_with_errno("setrlimit failed");
  2025. }
  2026. #else /* STACK_TRAP */
  2027. static WC_INLINE void StackTrap(void)
  2028. {
  2029. }
  2030. #endif /* STACK_TRAP */
  2031. #if defined(ATOMIC_USER) && !defined(WOLFSSL_AEAD_ONLY)
  2032. /* Atomic Encrypt Context example */
  2033. typedef struct AtomicEncCtx {
  2034. int keySetup; /* have we done key setup yet */
  2035. Aes aes; /* for aes example */
  2036. } AtomicEncCtx;
  2037. /* Atomic Decrypt Context example */
  2038. typedef struct AtomicDecCtx {
  2039. int keySetup; /* have we done key setup yet */
  2040. Aes aes; /* for aes example */
  2041. } AtomicDecCtx;
  2042. static WC_INLINE int myMacEncryptCb(WOLFSSL* ssl, unsigned char* macOut,
  2043. const unsigned char* macIn, unsigned int macInSz, int macContent,
  2044. int macVerify, unsigned char* encOut, const unsigned char* encIn,
  2045. unsigned int encSz, void* ctx)
  2046. {
  2047. int ret;
  2048. Hmac hmac;
  2049. byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
  2050. AtomicEncCtx* encCtx = (AtomicEncCtx*)ctx;
  2051. const char* tlsStr = "TLS";
  2052. /* example supports (d)tls aes */
  2053. if (wolfSSL_GetBulkCipher(ssl) != wolfssl_aes) {
  2054. printf("myMacEncryptCb not using AES\n");
  2055. return -1;
  2056. }
  2057. if (strstr(wolfSSL_get_version(ssl), tlsStr) == NULL) {
  2058. printf("myMacEncryptCb not using (D)TLS\n");
  2059. return -1;
  2060. }
  2061. /* hmac, not needed if aead mode */
  2062. wolfSSL_SetTlsHmacInner(ssl, myInner, macInSz, macContent, macVerify);
  2063. ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID);
  2064. if (ret != 0)
  2065. return ret;
  2066. ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
  2067. wolfSSL_GetMacSecret(ssl, macVerify), wolfSSL_GetHmacSize(ssl));
  2068. if (ret != 0)
  2069. return ret;
  2070. ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
  2071. if (ret != 0)
  2072. return ret;
  2073. ret = wc_HmacUpdate(&hmac, macIn, macInSz);
  2074. if (ret != 0)
  2075. return ret;
  2076. ret = wc_HmacFinal(&hmac, macOut);
  2077. if (ret != 0)
  2078. return ret;
  2079. /* encrypt setup on first time */
  2080. if (encCtx->keySetup == 0) {
  2081. int keyLen = wolfSSL_GetKeySize(ssl);
  2082. const byte* key;
  2083. const byte* iv;
  2084. if (wolfSSL_GetSide(ssl) == WOLFSSL_CLIENT_END) {
  2085. key = wolfSSL_GetClientWriteKey(ssl);
  2086. iv = wolfSSL_GetClientWriteIV(ssl);
  2087. }
  2088. else {
  2089. key = wolfSSL_GetServerWriteKey(ssl);
  2090. iv = wolfSSL_GetServerWriteIV(ssl);
  2091. }
  2092. ret = wc_AesSetKey(&encCtx->aes, key, keyLen, iv, AES_ENCRYPTION);
  2093. if (ret != 0) {
  2094. printf("AesSetKey failed in myMacEncryptCb\n");
  2095. return ret;
  2096. }
  2097. encCtx->keySetup = 1;
  2098. }
  2099. /* encrypt */
  2100. return wc_AesCbcEncrypt(&encCtx->aes, encOut, encIn, encSz);
  2101. }
  2102. static WC_INLINE int myDecryptVerifyCb(WOLFSSL* ssl,
  2103. unsigned char* decOut, const unsigned char* decIn,
  2104. unsigned int decSz, int macContent, int macVerify,
  2105. unsigned int* padSz, void* ctx)
  2106. {
  2107. AtomicDecCtx* decCtx = (AtomicDecCtx*)ctx;
  2108. int ret = 0;
  2109. int macInSz = 0;
  2110. int ivExtra = 0;
  2111. int digestSz = wolfSSL_GetHmacSize(ssl);
  2112. unsigned int pad = 0;
  2113. unsigned int padByte = 0;
  2114. Hmac hmac;
  2115. byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
  2116. byte verify[WC_MAX_DIGEST_SIZE];
  2117. const char* tlsStr = "TLS";
  2118. /* example supports (d)tls aes */
  2119. if (wolfSSL_GetBulkCipher(ssl) != wolfssl_aes) {
  2120. printf("myMacEncryptCb not using AES\n");
  2121. return -1;
  2122. }
  2123. if (strstr(wolfSSL_get_version(ssl), tlsStr) == NULL) {
  2124. printf("myMacEncryptCb not using (D)TLS\n");
  2125. return -1;
  2126. }
  2127. /*decrypt */
  2128. if (decCtx->keySetup == 0) {
  2129. int keyLen = wolfSSL_GetKeySize(ssl);
  2130. const byte* key;
  2131. const byte* iv;
  2132. /* decrypt is from other side (peer) */
  2133. if (wolfSSL_GetSide(ssl) == WOLFSSL_SERVER_END) {
  2134. key = wolfSSL_GetClientWriteKey(ssl);
  2135. iv = wolfSSL_GetClientWriteIV(ssl);
  2136. }
  2137. else {
  2138. key = wolfSSL_GetServerWriteKey(ssl);
  2139. iv = wolfSSL_GetServerWriteIV(ssl);
  2140. }
  2141. ret = wc_AesSetKey(&decCtx->aes, key, keyLen, iv, AES_DECRYPTION);
  2142. if (ret != 0) {
  2143. printf("AesSetKey failed in myDecryptVerifyCb\n");
  2144. return ret;
  2145. }
  2146. decCtx->keySetup = 1;
  2147. }
  2148. /* decrypt */
  2149. ret = wc_AesCbcDecrypt(&decCtx->aes, decOut, decIn, decSz);
  2150. if (ret != 0)
  2151. return ret;
  2152. if (wolfSSL_GetCipherType(ssl) == WOLFSSL_AEAD_TYPE) {
  2153. *padSz = wolfSSL_GetAeadMacSize(ssl);
  2154. return 0; /* hmac, not needed if aead mode */
  2155. }
  2156. if (wolfSSL_GetCipherType(ssl) == WOLFSSL_BLOCK_TYPE) {
  2157. pad = *(decOut + decSz - 1);
  2158. padByte = 1;
  2159. if (wolfSSL_IsTLSv1_1(ssl))
  2160. ivExtra = wolfSSL_GetCipherBlockSize(ssl);
  2161. }
  2162. *padSz = wolfSSL_GetHmacSize(ssl) + pad + padByte;
  2163. macInSz = decSz - ivExtra - digestSz - pad - padByte;
  2164. wolfSSL_SetTlsHmacInner(ssl, myInner, macInSz, macContent, macVerify);
  2165. ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID);
  2166. if (ret != 0)
  2167. return ret;
  2168. ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
  2169. wolfSSL_GetMacSecret(ssl, macVerify), digestSz);
  2170. if (ret != 0)
  2171. return ret;
  2172. ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
  2173. if (ret != 0)
  2174. return ret;
  2175. ret = wc_HmacUpdate(&hmac, decOut + ivExtra, macInSz);
  2176. if (ret != 0)
  2177. return ret;
  2178. ret = wc_HmacFinal(&hmac, verify);
  2179. if (ret != 0)
  2180. return ret;
  2181. if (XMEMCMP(verify, decOut + decSz - digestSz - pad - padByte,
  2182. digestSz) != 0) {
  2183. printf("myDecryptVerify verify failed\n");
  2184. return -1;
  2185. }
  2186. return ret;
  2187. }
  2188. #if defined(HAVE_ENCRYPT_THEN_MAC)
  2189. static WC_INLINE int myEncryptMacCb(WOLFSSL* ssl, unsigned char* macOut,
  2190. int content, int macVerify, unsigned char* encOut,
  2191. const unsigned char* encIn, unsigned int encSz, void* ctx)
  2192. {
  2193. int ret;
  2194. Hmac hmac;
  2195. AtomicEncCtx* encCtx = (AtomicEncCtx*)ctx;
  2196. byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
  2197. const char* tlsStr = "TLS";
  2198. /* example supports (d)tls aes */
  2199. if (wolfSSL_GetBulkCipher(ssl) != wolfssl_aes) {
  2200. printf("myMacEncryptCb not using AES\n");
  2201. return -1;
  2202. }
  2203. if (strstr(wolfSSL_get_version(ssl), tlsStr) == NULL) {
  2204. printf("myMacEncryptCb not using (D)TLS\n");
  2205. return -1;
  2206. }
  2207. /* encrypt setup on first time */
  2208. if (encCtx->keySetup == 0) {
  2209. int keyLen = wolfSSL_GetKeySize(ssl);
  2210. const byte* key;
  2211. const byte* iv;
  2212. if (wolfSSL_GetSide(ssl) == WOLFSSL_CLIENT_END) {
  2213. key = wolfSSL_GetClientWriteKey(ssl);
  2214. iv = wolfSSL_GetClientWriteIV(ssl);
  2215. }
  2216. else {
  2217. key = wolfSSL_GetServerWriteKey(ssl);
  2218. iv = wolfSSL_GetServerWriteIV(ssl);
  2219. }
  2220. ret = wc_AesSetKey(&encCtx->aes, key, keyLen, iv, AES_ENCRYPTION);
  2221. if (ret != 0) {
  2222. printf("AesSetKey failed in myMacEncryptCb\n");
  2223. return ret;
  2224. }
  2225. encCtx->keySetup = 1;
  2226. }
  2227. /* encrypt */
  2228. ret = wc_AesCbcEncrypt(&encCtx->aes, encOut, encIn, encSz);
  2229. if (ret != 0)
  2230. return ret;
  2231. /* Reconstruct record header. */
  2232. wolfSSL_SetTlsHmacInner(ssl, myInner, encSz, content, macVerify);
  2233. ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID);
  2234. if (ret != 0)
  2235. return ret;
  2236. ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
  2237. wolfSSL_GetMacSecret(ssl, macVerify), wolfSSL_GetHmacSize(ssl));
  2238. if (ret != 0)
  2239. return ret;
  2240. ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
  2241. if (ret != 0)
  2242. return ret;
  2243. ret = wc_HmacUpdate(&hmac, encOut, encSz);
  2244. if (ret != 0)
  2245. return ret;
  2246. return wc_HmacFinal(&hmac, macOut);
  2247. }
  2248. static WC_INLINE int myVerifyDecryptCb(WOLFSSL* ssl,
  2249. unsigned char* decOut, const unsigned char* decIn,
  2250. unsigned int decSz, int content, int macVerify,
  2251. unsigned int* padSz, void* ctx)
  2252. {
  2253. AtomicDecCtx* decCtx = (AtomicDecCtx*)ctx;
  2254. int ret = 0;
  2255. int digestSz = wolfSSL_GetHmacSize(ssl);
  2256. Hmac hmac;
  2257. byte myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
  2258. byte verify[WC_MAX_DIGEST_SIZE];
  2259. const char* tlsStr = "TLS";
  2260. /* example supports (d)tls aes */
  2261. if (wolfSSL_GetBulkCipher(ssl) != wolfssl_aes) {
  2262. printf("myMacEncryptCb not using AES\n");
  2263. return -1;
  2264. }
  2265. if (strstr(wolfSSL_get_version(ssl), tlsStr) == NULL) {
  2266. printf("myMacEncryptCb not using (D)TLS\n");
  2267. return -1;
  2268. }
  2269. /* Reconstruct record header. */
  2270. wolfSSL_SetTlsHmacInner(ssl, myInner, decSz, content, macVerify);
  2271. ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID);
  2272. if (ret != 0)
  2273. return ret;
  2274. ret = wc_HmacSetKey(&hmac, wolfSSL_GetHmacType(ssl),
  2275. wolfSSL_GetMacSecret(ssl, macVerify), digestSz);
  2276. if (ret != 0)
  2277. return ret;
  2278. ret = wc_HmacUpdate(&hmac, myInner, sizeof(myInner));
  2279. if (ret != 0)
  2280. return ret;
  2281. ret = wc_HmacUpdate(&hmac, decIn, decSz);
  2282. if (ret != 0)
  2283. return ret;
  2284. ret = wc_HmacFinal(&hmac, verify);
  2285. if (ret != 0)
  2286. return ret;
  2287. if (XMEMCMP(verify, decOut + decSz, digestSz) != 0) {
  2288. printf("myDecryptVerify verify failed\n");
  2289. return -1;
  2290. }
  2291. /* decrypt */
  2292. if (decCtx->keySetup == 0) {
  2293. int keyLen = wolfSSL_GetKeySize(ssl);
  2294. const byte* key;
  2295. const byte* iv;
  2296. /* decrypt is from other side (peer) */
  2297. if (wolfSSL_GetSide(ssl) == WOLFSSL_SERVER_END) {
  2298. key = wolfSSL_GetClientWriteKey(ssl);
  2299. iv = wolfSSL_GetClientWriteIV(ssl);
  2300. }
  2301. else {
  2302. key = wolfSSL_GetServerWriteKey(ssl);
  2303. iv = wolfSSL_GetServerWriteIV(ssl);
  2304. }
  2305. ret = wc_AesSetKey(&decCtx->aes, key, keyLen, iv, AES_DECRYPTION);
  2306. if (ret != 0) {
  2307. printf("AesSetKey failed in myDecryptVerifyCb\n");
  2308. return ret;
  2309. }
  2310. decCtx->keySetup = 1;
  2311. }
  2312. /* decrypt */
  2313. ret = wc_AesCbcDecrypt(&decCtx->aes, decOut, decIn, decSz);
  2314. if (ret != 0)
  2315. return ret;
  2316. *padSz = *(decOut + decSz - 1) + 1;
  2317. return 0;
  2318. }
  2319. #endif
  2320. static WC_INLINE void SetupAtomicUser(WOLFSSL_CTX* ctx, WOLFSSL* ssl)
  2321. {
  2322. AtomicEncCtx* encCtx;
  2323. AtomicDecCtx* decCtx;
  2324. encCtx = (AtomicEncCtx*)malloc(sizeof(AtomicEncCtx));
  2325. if (encCtx == NULL)
  2326. err_sys_with_errno("AtomicEncCtx malloc failed");
  2327. XMEMSET(encCtx, 0, sizeof(AtomicEncCtx));
  2328. decCtx = (AtomicDecCtx*)malloc(sizeof(AtomicDecCtx));
  2329. if (decCtx == NULL) {
  2330. free(encCtx);
  2331. err_sys_with_errno("AtomicDecCtx malloc failed");
  2332. }
  2333. XMEMSET(decCtx, 0, sizeof(AtomicDecCtx));
  2334. wolfSSL_CTX_SetMacEncryptCb(ctx, myMacEncryptCb);
  2335. wolfSSL_SetMacEncryptCtx(ssl, encCtx);
  2336. wolfSSL_CTX_SetDecryptVerifyCb(ctx, myDecryptVerifyCb);
  2337. wolfSSL_SetDecryptVerifyCtx(ssl, decCtx);
  2338. #if defined(HAVE_ENCRYPT_THEN_MAC)
  2339. wolfSSL_CTX_SetEncryptMacCb(ctx, myEncryptMacCb);
  2340. wolfSSL_SetEncryptMacCtx(ssl, encCtx);
  2341. wolfSSL_CTX_SetVerifyDecryptCb(ctx, myVerifyDecryptCb);
  2342. wolfSSL_SetVerifyDecryptCtx(ssl, decCtx);
  2343. #endif
  2344. }
  2345. static WC_INLINE void FreeAtomicUser(WOLFSSL* ssl)
  2346. {
  2347. AtomicEncCtx* encCtx = (AtomicEncCtx*)wolfSSL_GetMacEncryptCtx(ssl);
  2348. AtomicDecCtx* decCtx = (AtomicDecCtx*)wolfSSL_GetDecryptVerifyCtx(ssl);
  2349. /* Encrypt-Then-MAC callbacks use same contexts. */
  2350. free(decCtx);
  2351. free(encCtx);
  2352. }
  2353. #endif /* ATOMIC_USER */
  2354. #ifdef WOLFSSL_STATIC_MEMORY
  2355. static WC_INLINE int wolfSSL_PrintStats(WOLFSSL_MEM_STATS* stats)
  2356. {
  2357. word16 i;
  2358. if (stats == NULL) {
  2359. return 0;
  2360. }
  2361. /* print to stderr so is on the same pipe as WOLFSSL_DEBUG */
  2362. fprintf(stderr, "Total mallocs = %d\n", stats->totalAlloc);
  2363. fprintf(stderr, "Total frees = %d\n", stats->totalFr);
  2364. fprintf(stderr, "Current mallocs = %d\n", stats->curAlloc);
  2365. fprintf(stderr, "Available IO = %d\n", stats->avaIO);
  2366. fprintf(stderr, "Max con. handshakes = %d\n", stats->maxHa);
  2367. fprintf(stderr, "Max con. IO = %d\n", stats->maxIO);
  2368. fprintf(stderr, "State of memory blocks: size : available \n");
  2369. for (i = 0; i < WOLFMEM_MAX_BUCKETS; i++) {
  2370. fprintf(stderr, " : %d\t : %d\n", stats->blockSz[i],
  2371. stats->avaBlock[i]);
  2372. }
  2373. return 1;
  2374. }
  2375. #endif /* WOLFSSL_STATIC_MEMORY */
  2376. #ifdef HAVE_PK_CALLBACKS
  2377. typedef struct PkCbInfo {
  2378. const char* ourKey;
  2379. #ifdef TEST_PK_PRIVKEY
  2380. union {
  2381. #ifdef HAVE_ECC
  2382. ecc_key ecc;
  2383. #endif
  2384. #ifdef HAVE_CURVE25519
  2385. curve25519_key curve;
  2386. #endif
  2387. #ifdef HAVE_CURVE448
  2388. curve448_key curve;
  2389. #endif
  2390. } keyGen;
  2391. #endif
  2392. } PkCbInfo;
  2393. #if defined(DEBUG_PK_CB) || defined(TEST_PK_PRIVKEY)
  2394. #define WOLFSSL_PKMSG(_f_, ...) printf(_f_, ##__VA_ARGS__)
  2395. #else
  2396. #define WOLFSSL_PKMSG(_f_, ...)
  2397. #endif
  2398. #ifdef HAVE_ECC
  2399. static WC_INLINE int myEccKeyGen(WOLFSSL* ssl, ecc_key* key, word32 keySz,
  2400. int ecc_curve, void* ctx)
  2401. {
  2402. int ret;
  2403. WC_RNG rng;
  2404. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2405. ecc_key* new_key;
  2406. #ifdef TEST_PK_PRIVKEY
  2407. byte qx[MAX_ECC_BYTES], qy[MAX_ECC_BYTES];
  2408. word32 qxLen = sizeof(qx), qyLen = sizeof(qy);
  2409. new_key = &cbInfo->keyGen.ecc;
  2410. #else
  2411. new_key = key;
  2412. #endif
  2413. (void)ssl;
  2414. (void)cbInfo;
  2415. WOLFSSL_PKMSG("PK ECC KeyGen: keySz %d, Curve ID %d\n", keySz, ecc_curve);
  2416. ret = wc_InitRng(&rng);
  2417. if (ret != 0)
  2418. return ret;
  2419. ret = wc_ecc_init(new_key);
  2420. if (ret == 0) {
  2421. /* create new key */
  2422. ret = wc_ecc_make_key_ex(&rng, keySz, new_key, ecc_curve);
  2423. #ifdef TEST_PK_PRIVKEY
  2424. if (ret == 0) {
  2425. /* extract public portion from new key into `key` arg */
  2426. ret = wc_ecc_export_public_raw(new_key, qx, &qxLen, qy, &qyLen);
  2427. if (ret == 0) {
  2428. /* load public portion only into key */
  2429. ret = wc_ecc_import_unsigned(key, qx, qy, NULL, ecc_curve);
  2430. }
  2431. (void)qxLen;
  2432. (void)qyLen;
  2433. }
  2434. #endif
  2435. }
  2436. WOLFSSL_PKMSG("PK ECC KeyGen: ret %d\n", ret);
  2437. wc_FreeRng(&rng);
  2438. return ret;
  2439. }
  2440. static WC_INLINE int myEccSign(WOLFSSL* ssl, const byte* in, word32 inSz,
  2441. byte* out, word32* outSz, const byte* key, word32 keySz, void* ctx)
  2442. {
  2443. int ret;
  2444. WC_RNG rng;
  2445. word32 idx = 0;
  2446. ecc_key myKey;
  2447. byte* keyBuf = (byte*)key;
  2448. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2449. (void)ssl;
  2450. (void)cbInfo;
  2451. WOLFSSL_PKMSG("PK ECC Sign: inSz %d, keySz %d\n", inSz, keySz);
  2452. #ifdef TEST_PK_PRIVKEY
  2453. ret = load_key_file(cbInfo->ourKey, &keyBuf, &keySz);
  2454. if (ret != 0)
  2455. return ret;
  2456. #endif
  2457. ret = wc_InitRng(&rng);
  2458. if (ret != 0)
  2459. return ret;
  2460. ret = wc_ecc_init(&myKey);
  2461. if (ret == 0) {
  2462. ret = wc_EccPrivateKeyDecode(keyBuf, &idx, &myKey, keySz);
  2463. if (ret == 0) {
  2464. WOLFSSL_PKMSG("PK ECC Sign: Curve ID %d\n", myKey.dp->id);
  2465. ret = wc_ecc_sign_hash(in, inSz, out, outSz, &rng, &myKey);
  2466. }
  2467. wc_ecc_free(&myKey);
  2468. }
  2469. wc_FreeRng(&rng);
  2470. #ifdef TEST_PK_PRIVKEY
  2471. free(keyBuf);
  2472. #endif
  2473. WOLFSSL_PKMSG("PK ECC Sign: ret %d outSz %d\n", ret, *outSz);
  2474. return ret;
  2475. }
  2476. static WC_INLINE int myEccVerify(WOLFSSL* ssl, const byte* sig, word32 sigSz,
  2477. const byte* hash, word32 hashSz, const byte* key, word32 keySz,
  2478. int* result, void* ctx)
  2479. {
  2480. int ret;
  2481. word32 idx = 0;
  2482. ecc_key myKey;
  2483. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2484. (void)ssl;
  2485. (void)cbInfo;
  2486. WOLFSSL_PKMSG("PK ECC Verify: sigSz %d, hashSz %d, keySz %d\n", sigSz, hashSz, keySz);
  2487. ret = wc_ecc_init(&myKey);
  2488. if (ret == 0) {
  2489. ret = wc_EccPublicKeyDecode(key, &idx, &myKey, keySz);
  2490. if (ret == 0)
  2491. ret = wc_ecc_verify_hash(sig, sigSz, hash, hashSz, result, &myKey);
  2492. wc_ecc_free(&myKey);
  2493. }
  2494. WOLFSSL_PKMSG("PK ECC Verify: ret %d, result %d\n", ret, *result);
  2495. return ret;
  2496. }
  2497. static WC_INLINE int myEccSharedSecret(WOLFSSL* ssl, ecc_key* otherKey,
  2498. unsigned char* pubKeyDer, unsigned int* pubKeySz,
  2499. unsigned char* out, unsigned int* outlen,
  2500. int side, void* ctx)
  2501. {
  2502. int ret;
  2503. ecc_key* privKey = NULL;
  2504. ecc_key* pubKey = NULL;
  2505. ecc_key tmpKey;
  2506. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2507. (void)ssl;
  2508. (void)cbInfo;
  2509. WOLFSSL_PKMSG("PK ECC PMS: Side %s, Peer Curve %d\n",
  2510. side == WOLFSSL_CLIENT_END ? "client" : "server", otherKey->dp->id);
  2511. ret = wc_ecc_init(&tmpKey);
  2512. if (ret != 0) {
  2513. return ret;
  2514. }
  2515. /* for client: create and export public key */
  2516. if (side == WOLFSSL_CLIENT_END) {
  2517. WC_RNG rng;
  2518. privKey = &tmpKey;
  2519. pubKey = otherKey;
  2520. ret = wc_InitRng(&rng);
  2521. if (ret == 0) {
  2522. ret = wc_ecc_make_key_ex(&rng, 0, privKey, otherKey->dp->id);
  2523. #ifdef WOLFSSL_ASYNC_CRYPT
  2524. if (ret == WC_PENDING_E) {
  2525. ret = wc_AsyncWait(ret, &privKey->asyncDev, WC_ASYNC_FLAG_NONE);
  2526. }
  2527. #endif
  2528. if (ret == 0)
  2529. ret = wc_ecc_export_x963(privKey, pubKeyDer, pubKeySz);
  2530. wc_FreeRng(&rng);
  2531. }
  2532. }
  2533. /* for server: import public key */
  2534. else if (side == WOLFSSL_SERVER_END) {
  2535. #ifdef TEST_PK_PRIVKEY
  2536. privKey = &cbInfo->keyGen.ecc;
  2537. #else
  2538. privKey = otherKey;
  2539. #endif
  2540. pubKey = &tmpKey;
  2541. ret = wc_ecc_import_x963_ex(pubKeyDer, *pubKeySz, pubKey,
  2542. otherKey->dp->id);
  2543. }
  2544. else {
  2545. ret = BAD_FUNC_ARG;
  2546. }
  2547. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_FIPS) && \
  2548. !defined(HAVE_SELFTEST)
  2549. if (ret == 0) {
  2550. ret = wc_ecc_set_rng(privKey, wolfSSL_GetRNG(ssl));
  2551. }
  2552. #endif
  2553. /* generate shared secret and return it */
  2554. if (ret == 0) {
  2555. ret = wc_ecc_shared_secret(privKey, pubKey, out, outlen);
  2556. #ifdef WOLFSSL_ASYNC_CRYPT
  2557. if (ret == WC_PENDING_E) {
  2558. ret = wc_AsyncWait(ret, &privKey->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  2559. }
  2560. #endif
  2561. }
  2562. #ifdef TEST_PK_PRIVKEY
  2563. if (side == WOLFSSL_SERVER_END) {
  2564. wc_ecc_free(&cbInfo->keyGen.ecc);
  2565. }
  2566. #endif
  2567. wc_ecc_free(&tmpKey);
  2568. WOLFSSL_PKMSG("PK ECC PMS: ret %d, PubKeySz %d, OutLen %d\n", ret, *pubKeySz, *outlen);
  2569. return ret;
  2570. }
  2571. #ifdef HAVE_ED25519
  2572. static WC_INLINE int myEd25519Sign(WOLFSSL* ssl, const byte* in, word32 inSz,
  2573. byte* out, word32* outSz, const byte* key, word32 keySz, void* ctx)
  2574. {
  2575. int ret;
  2576. word32 idx = 0;
  2577. ed25519_key myKey;
  2578. byte* keyBuf = (byte*)key;
  2579. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2580. (void)ssl;
  2581. (void)cbInfo;
  2582. WOLFSSL_PKMSG("PK 25519 Sign: inSz %d, keySz %d\n", inSz, keySz);
  2583. #ifdef TEST_PK_PRIVKEY
  2584. ret = load_key_file(cbInfo->ourKey, &keyBuf, &keySz);
  2585. if (ret != 0)
  2586. return ret;
  2587. #endif
  2588. ret = wc_ed25519_init(&myKey);
  2589. if (ret == 0) {
  2590. ret = wc_Ed25519PrivateKeyDecode(keyBuf, &idx, &myKey, keySz);
  2591. if (ret == 0)
  2592. ret = wc_ed25519_sign_msg(in, inSz, out, outSz, &myKey);
  2593. wc_ed25519_free(&myKey);
  2594. }
  2595. #ifdef TEST_PK_PRIVKEY
  2596. free(keyBuf);
  2597. #endif
  2598. WOLFSSL_PKMSG("PK 25519 Sign: ret %d, outSz %d\n", ret, *outSz);
  2599. return ret;
  2600. }
  2601. static WC_INLINE int myEd25519Verify(WOLFSSL* ssl, const byte* sig, word32 sigSz,
  2602. const byte* msg, word32 msgSz, const byte* key, word32 keySz,
  2603. int* result, void* ctx)
  2604. {
  2605. int ret;
  2606. ed25519_key myKey;
  2607. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2608. (void)ssl;
  2609. (void)cbInfo;
  2610. WOLFSSL_PKMSG("PK 25519 Verify: sigSz %d, msgSz %d, keySz %d\n", sigSz, msgSz, keySz);
  2611. ret = wc_ed25519_init(&myKey);
  2612. if (ret == 0) {
  2613. ret = wc_ed25519_import_public(key, keySz, &myKey);
  2614. if (ret == 0) {
  2615. ret = wc_ed25519_verify_msg(sig, sigSz, msg, msgSz, result, &myKey);
  2616. }
  2617. wc_ed25519_free(&myKey);
  2618. }
  2619. WOLFSSL_PKMSG("PK 25519 Verify: ret %d, result %d\n", ret, *result);
  2620. return ret;
  2621. }
  2622. #endif /* HAVE_ED25519 */
  2623. #ifdef HAVE_CURVE25519
  2624. static WC_INLINE int myX25519KeyGen(WOLFSSL* ssl, curve25519_key* key,
  2625. unsigned int keySz, void* ctx)
  2626. {
  2627. int ret;
  2628. WC_RNG rng;
  2629. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2630. (void)ssl;
  2631. (void)cbInfo;
  2632. WOLFSSL_PKMSG("PK 25519 KeyGen: keySz %d\n", keySz);
  2633. ret = wc_InitRng(&rng);
  2634. if (ret != 0)
  2635. return ret;
  2636. ret = wc_curve25519_make_key(&rng, keySz, key);
  2637. wc_FreeRng(&rng);
  2638. WOLFSSL_PKMSG("PK 25519 KeyGen: ret %d\n", ret);
  2639. return ret;
  2640. }
  2641. static WC_INLINE int myX25519SharedSecret(WOLFSSL* ssl, curve25519_key* otherKey,
  2642. unsigned char* pubKeyDer, unsigned int* pubKeySz,
  2643. unsigned char* out, unsigned int* outlen,
  2644. int side, void* ctx)
  2645. {
  2646. int ret;
  2647. curve25519_key* privKey = NULL;
  2648. curve25519_key* pubKey = NULL;
  2649. curve25519_key tmpKey;
  2650. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2651. (void)ssl;
  2652. (void)cbInfo;
  2653. WOLFSSL_PKMSG("PK 25519 PMS: side %s\n",
  2654. side == WOLFSSL_CLIENT_END ? "client" : "server");
  2655. ret = wc_curve25519_init(&tmpKey);
  2656. if (ret != 0) {
  2657. return ret;
  2658. }
  2659. /* for client: create and export public key */
  2660. if (side == WOLFSSL_CLIENT_END) {
  2661. WC_RNG rng;
  2662. privKey = &tmpKey;
  2663. pubKey = otherKey;
  2664. ret = wc_InitRng(&rng);
  2665. if (ret == 0) {
  2666. ret = wc_curve25519_make_key(&rng, CURVE25519_KEYSIZE, privKey);
  2667. if (ret == 0) {
  2668. ret = wc_curve25519_export_public_ex(privKey, pubKeyDer,
  2669. pubKeySz, EC25519_LITTLE_ENDIAN);
  2670. }
  2671. wc_FreeRng(&rng);
  2672. }
  2673. }
  2674. /* for server: import public key */
  2675. else if (side == WOLFSSL_SERVER_END) {
  2676. privKey = otherKey;
  2677. pubKey = &tmpKey;
  2678. ret = wc_curve25519_import_public_ex(pubKeyDer, *pubKeySz, pubKey,
  2679. EC25519_LITTLE_ENDIAN);
  2680. }
  2681. else {
  2682. ret = BAD_FUNC_ARG;
  2683. }
  2684. /* generate shared secret and return it */
  2685. if (ret == 0) {
  2686. ret = wc_curve25519_shared_secret_ex(privKey, pubKey, out, outlen,
  2687. EC25519_LITTLE_ENDIAN);
  2688. }
  2689. wc_curve25519_free(&tmpKey);
  2690. WOLFSSL_PKMSG("PK 25519 PMS: ret %d, pubKeySz %d, outLen %d\n",
  2691. ret, *pubKeySz, *outlen);
  2692. return ret;
  2693. }
  2694. #endif /* HAVE_CURVE25519 */
  2695. #ifdef HAVE_ED448
  2696. static WC_INLINE int myEd448Sign(WOLFSSL* ssl, const byte* in, word32 inSz,
  2697. byte* out, word32* outSz, const byte* key, word32 keySz, void* ctx)
  2698. {
  2699. int ret;
  2700. word32 idx = 0;
  2701. ed448_key myKey;
  2702. byte* keyBuf = (byte*)key;
  2703. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2704. (void)ssl;
  2705. (void)cbInfo;
  2706. WOLFSSL_PKMSG("PK 448 Sign: inSz %d, keySz %d\n", inSz, keySz);
  2707. #ifdef TEST_PK_PRIVKEY
  2708. ret = load_key_file(cbInfo->ourKey, &keyBuf, &keySz);
  2709. if (ret != 0)
  2710. return ret;
  2711. #endif
  2712. ret = wc_ed448_init(&myKey);
  2713. if (ret == 0) {
  2714. ret = wc_Ed448PrivateKeyDecode(keyBuf, &idx, &myKey, keySz);
  2715. if (ret == 0)
  2716. ret = wc_ed448_sign_msg(in, inSz, out, outSz, &myKey, NULL, 0);
  2717. wc_ed448_free(&myKey);
  2718. }
  2719. #ifdef TEST_PK_PRIVKEY
  2720. free(keyBuf);
  2721. #endif
  2722. WOLFSSL_PKMSG("PK 448 Sign: ret %d, outSz %d\n", ret, *outSz);
  2723. return ret;
  2724. }
  2725. static WC_INLINE int myEd448Verify(WOLFSSL* ssl, const byte* sig, word32 sigSz,
  2726. const byte* msg, word32 msgSz, const byte* key, word32 keySz,
  2727. int* result, void* ctx)
  2728. {
  2729. int ret;
  2730. ed448_key myKey;
  2731. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2732. (void)ssl;
  2733. (void)cbInfo;
  2734. WOLFSSL_PKMSG("PK 448 Verify: sigSz %d, msgSz %d, keySz %d\n", sigSz, msgSz,
  2735. keySz);
  2736. ret = wc_ed448_init(&myKey);
  2737. if (ret == 0) {
  2738. ret = wc_ed448_import_public(key, keySz, &myKey);
  2739. if (ret == 0) {
  2740. ret = wc_ed448_verify_msg(sig, sigSz, msg, msgSz, result, &myKey,
  2741. NULL, 0);
  2742. }
  2743. wc_ed448_free(&myKey);
  2744. }
  2745. WOLFSSL_PKMSG("PK 448 Verify: ret %d, result %d\n", ret, *result);
  2746. return ret;
  2747. }
  2748. #endif /* HAVE_ED448 */
  2749. #ifdef HAVE_CURVE448
  2750. static WC_INLINE int myX448KeyGen(WOLFSSL* ssl, curve448_key* key,
  2751. unsigned int keySz, void* ctx)
  2752. {
  2753. int ret;
  2754. WC_RNG rng;
  2755. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2756. (void)ssl;
  2757. (void)cbInfo;
  2758. WOLFSSL_PKMSG("PK 448 KeyGen: keySz %d\n", keySz);
  2759. ret = wc_InitRng(&rng);
  2760. if (ret != 0)
  2761. return ret;
  2762. ret = wc_curve448_make_key(&rng, keySz, key);
  2763. wc_FreeRng(&rng);
  2764. WOLFSSL_PKMSG("PK 448 KeyGen: ret %d\n", ret);
  2765. return ret;
  2766. }
  2767. static WC_INLINE int myX448SharedSecret(WOLFSSL* ssl, curve448_key* otherKey,
  2768. unsigned char* pubKeyDer, unsigned int* pubKeySz,
  2769. unsigned char* out, unsigned int* outlen,
  2770. int side, void* ctx)
  2771. {
  2772. int ret;
  2773. curve448_key* privKey = NULL;
  2774. curve448_key* pubKey = NULL;
  2775. curve448_key tmpKey;
  2776. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2777. (void)ssl;
  2778. (void)cbInfo;
  2779. WOLFSSL_PKMSG("PK 448 PMS: side %s\n",
  2780. side == WOLFSSL_CLIENT_END ? "client" : "server");
  2781. ret = wc_curve448_init(&tmpKey);
  2782. if (ret != 0) {
  2783. return ret;
  2784. }
  2785. /* for client: create and export public key */
  2786. if (side == WOLFSSL_CLIENT_END) {
  2787. WC_RNG rng;
  2788. privKey = &tmpKey;
  2789. pubKey = otherKey;
  2790. ret = wc_InitRng(&rng);
  2791. if (ret == 0) {
  2792. ret = wc_curve448_make_key(&rng, CURVE448_KEY_SIZE, privKey);
  2793. if (ret == 0) {
  2794. ret = wc_curve448_export_public_ex(privKey, pubKeyDer,
  2795. pubKeySz, EC448_LITTLE_ENDIAN);
  2796. }
  2797. wc_FreeRng(&rng);
  2798. }
  2799. }
  2800. /* for server: import public key */
  2801. else if (side == WOLFSSL_SERVER_END) {
  2802. privKey = otherKey;
  2803. pubKey = &tmpKey;
  2804. ret = wc_curve448_import_public_ex(pubKeyDer, *pubKeySz, pubKey,
  2805. EC448_LITTLE_ENDIAN);
  2806. }
  2807. else {
  2808. ret = BAD_FUNC_ARG;
  2809. }
  2810. /* generate shared secret and return it */
  2811. if (ret == 0) {
  2812. ret = wc_curve448_shared_secret_ex(privKey, pubKey, out, outlen,
  2813. EC448_LITTLE_ENDIAN);
  2814. }
  2815. wc_curve448_free(&tmpKey);
  2816. WOLFSSL_PKMSG("PK 448 PMS: ret %d, pubKeySz %d, outLen %d\n",
  2817. ret, *pubKeySz, *outlen);
  2818. return ret;
  2819. }
  2820. #endif /* HAVE_CURVE448 */
  2821. #endif /* HAVE_ECC */
  2822. #ifndef NO_DH
  2823. static WC_INLINE int myDhCallback(WOLFSSL* ssl, struct DhKey* key,
  2824. const unsigned char* priv, unsigned int privSz,
  2825. const unsigned char* pubKeyDer, unsigned int pubKeySz,
  2826. unsigned char* out, unsigned int* outlen,
  2827. void* ctx)
  2828. {
  2829. int ret;
  2830. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2831. (void)ssl;
  2832. (void)cbInfo;
  2833. /* return 0 on success */
  2834. ret = wc_DhAgree(key, out, outlen, priv, privSz, pubKeyDer, pubKeySz);
  2835. WOLFSSL_PKMSG("PK ED Agree: ret %d, privSz %d, pubKeySz %d, outlen %d\n",
  2836. ret, privSz, pubKeySz, *outlen);
  2837. return ret;
  2838. };
  2839. #endif /* !NO_DH */
  2840. #ifndef NO_RSA
  2841. static WC_INLINE int myRsaSign(WOLFSSL* ssl, const byte* in, word32 inSz,
  2842. byte* out, word32* outSz, const byte* key, word32 keySz, void* ctx)
  2843. {
  2844. WC_RNG rng;
  2845. int ret;
  2846. word32 idx = 0;
  2847. RsaKey myKey;
  2848. byte* keyBuf = (byte*)key;
  2849. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2850. (void)ssl;
  2851. (void)cbInfo;
  2852. WOLFSSL_PKMSG("PK RSA Sign: inSz %d, keySz %d\n", inSz, keySz);
  2853. #ifdef TEST_PK_PRIVKEY
  2854. ret = load_key_file(cbInfo->ourKey, &keyBuf, &keySz);
  2855. if (ret != 0)
  2856. return ret;
  2857. #endif
  2858. ret = wc_InitRng(&rng);
  2859. if (ret != 0)
  2860. return ret;
  2861. ret = wc_InitRsaKey(&myKey, NULL);
  2862. if (ret == 0) {
  2863. ret = wc_RsaPrivateKeyDecode(keyBuf, &idx, &myKey, keySz);
  2864. if (ret == 0)
  2865. ret = wc_RsaSSL_Sign(in, inSz, out, *outSz, &myKey, &rng);
  2866. if (ret > 0) { /* save and convert to 0 success */
  2867. *outSz = ret;
  2868. ret = 0;
  2869. }
  2870. wc_FreeRsaKey(&myKey);
  2871. }
  2872. wc_FreeRng(&rng);
  2873. #ifdef TEST_PK_PRIVKEY
  2874. free(keyBuf);
  2875. #endif
  2876. WOLFSSL_PKMSG("PK RSA Sign: ret %d, outSz %d\n", ret, *outSz);
  2877. return ret;
  2878. }
  2879. static WC_INLINE int myRsaVerify(WOLFSSL* ssl, byte* sig, word32 sigSz,
  2880. byte** out, const byte* key, word32 keySz, void* ctx)
  2881. {
  2882. int ret;
  2883. word32 idx = 0;
  2884. RsaKey myKey;
  2885. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2886. (void)ssl;
  2887. (void)cbInfo;
  2888. WOLFSSL_PKMSG("PK RSA Verify: sigSz %d, keySz %d\n", sigSz, keySz);
  2889. ret = wc_InitRsaKey(&myKey, NULL);
  2890. if (ret == 0) {
  2891. ret = wc_RsaPublicKeyDecode(key, &idx, &myKey, keySz);
  2892. if (ret == 0)
  2893. ret = wc_RsaSSL_VerifyInline(sig, sigSz, out, &myKey);
  2894. wc_FreeRsaKey(&myKey);
  2895. }
  2896. WOLFSSL_PKMSG("PK RSA Verify: ret %d\n", ret);
  2897. return ret;
  2898. }
  2899. static WC_INLINE int myRsaSignCheck(WOLFSSL* ssl, byte* sig, word32 sigSz,
  2900. byte** out, const byte* key, word32 keySz, void* ctx)
  2901. {
  2902. int ret;
  2903. word32 idx = 0;
  2904. RsaKey myKey;
  2905. byte* keyBuf = (byte*)key;
  2906. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2907. (void)ssl;
  2908. (void)cbInfo;
  2909. WOLFSSL_PKMSG("PK RSA SignCheck: sigSz %d, keySz %d\n", sigSz, keySz);
  2910. #ifdef TEST_PK_PRIVKEY
  2911. ret = load_key_file(cbInfo->ourKey, &keyBuf, &keySz);
  2912. if (ret != 0)
  2913. return ret;
  2914. #endif
  2915. ret = wc_InitRsaKey(&myKey, NULL);
  2916. if (ret == 0) {
  2917. ret = wc_RsaPrivateKeyDecode(keyBuf, &idx, &myKey, keySz);
  2918. if (ret == 0)
  2919. ret = wc_RsaSSL_VerifyInline(sig, sigSz, out, &myKey);
  2920. wc_FreeRsaKey(&myKey);
  2921. }
  2922. #ifdef TEST_PK_PRIVKEY
  2923. free(keyBuf);
  2924. #endif
  2925. WOLFSSL_PKMSG("PK RSA SignCheck: ret %d\n", ret);
  2926. return ret;
  2927. }
  2928. #ifdef WC_RSA_PSS
  2929. static WC_INLINE int myRsaPssSign(WOLFSSL* ssl, const byte* in, word32 inSz,
  2930. byte* out, word32* outSz, int hash, int mgf, const byte* key,
  2931. word32 keySz, void* ctx)
  2932. {
  2933. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  2934. WC_RNG rng;
  2935. int ret;
  2936. word32 idx = 0;
  2937. RsaKey myKey;
  2938. byte* keyBuf = (byte*)key;
  2939. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2940. (void)ssl;
  2941. (void)cbInfo;
  2942. WOLFSSL_PKMSG("PK RSA PSS Sign: inSz %d, hash %d, mgf %d, keySz %d\n",
  2943. inSz, hash, mgf, keySz);
  2944. #ifdef TEST_PK_PRIVKEY
  2945. ret = load_key_file(cbInfo->ourKey, &keyBuf, &keySz);
  2946. if (ret != 0)
  2947. return ret;
  2948. #endif
  2949. switch (hash) {
  2950. #ifndef NO_SHA256
  2951. case SHA256h:
  2952. hashType = WC_HASH_TYPE_SHA256;
  2953. break;
  2954. #endif
  2955. #ifdef WOLFSSL_SHA384
  2956. case SHA384h:
  2957. hashType = WC_HASH_TYPE_SHA384;
  2958. break;
  2959. #endif
  2960. #ifdef WOLFSSL_SHA512
  2961. case SHA512h:
  2962. hashType = WC_HASH_TYPE_SHA512;
  2963. break;
  2964. #endif
  2965. }
  2966. ret = wc_InitRng(&rng);
  2967. if (ret != 0)
  2968. return ret;
  2969. ret = wc_InitRsaKey(&myKey, NULL);
  2970. if (ret == 0) {
  2971. ret = wc_RsaPrivateKeyDecode(keyBuf, &idx, &myKey, keySz);
  2972. if (ret == 0) {
  2973. ret = wc_RsaPSS_Sign(in, inSz, out, *outSz, hashType, mgf, &myKey,
  2974. &rng);
  2975. }
  2976. if (ret > 0) { /* save and convert to 0 success */
  2977. *outSz = ret;
  2978. ret = 0;
  2979. }
  2980. wc_FreeRsaKey(&myKey);
  2981. }
  2982. wc_FreeRng(&rng);
  2983. #ifdef TEST_PK_PRIVKEY
  2984. free(keyBuf);
  2985. #endif
  2986. WOLFSSL_PKMSG("PK RSA PSS Sign: ret %d, outSz %d\n", ret, *outSz);
  2987. return ret;
  2988. }
  2989. static WC_INLINE int myRsaPssVerify(WOLFSSL* ssl, byte* sig, word32 sigSz,
  2990. byte** out, int hash, int mgf, const byte* key, word32 keySz, void* ctx)
  2991. {
  2992. int ret;
  2993. word32 idx = 0;
  2994. RsaKey myKey;
  2995. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  2996. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  2997. (void)ssl;
  2998. (void)cbInfo;
  2999. WOLFSSL_PKMSG("PK RSA PSS Verify: sigSz %d, hash %d, mgf %d, keySz %d\n",
  3000. sigSz, hash, mgf, keySz);
  3001. switch (hash) {
  3002. #ifndef NO_SHA256
  3003. case SHA256h:
  3004. hashType = WC_HASH_TYPE_SHA256;
  3005. break;
  3006. #endif
  3007. #ifdef WOLFSSL_SHA384
  3008. case SHA384h:
  3009. hashType = WC_HASH_TYPE_SHA384;
  3010. break;
  3011. #endif
  3012. #ifdef WOLFSSL_SHA512
  3013. case SHA512h:
  3014. hashType = WC_HASH_TYPE_SHA512;
  3015. break;
  3016. #endif
  3017. }
  3018. ret = wc_InitRsaKey(&myKey, NULL);
  3019. if (ret == 0) {
  3020. ret = wc_RsaPublicKeyDecode(key, &idx, &myKey, keySz);
  3021. if (ret == 0) {
  3022. ret = wc_RsaPSS_VerifyInline(sig, sigSz, out, hashType, mgf,
  3023. &myKey);
  3024. }
  3025. wc_FreeRsaKey(&myKey);
  3026. }
  3027. WOLFSSL_PKMSG("PK RSA PSS Verify: ret %d\n", ret);
  3028. return ret;
  3029. }
  3030. static WC_INLINE int myRsaPssSignCheck(WOLFSSL* ssl, byte* sig, word32 sigSz,
  3031. byte** out, int hash, int mgf, const byte* key, word32 keySz, void* ctx)
  3032. {
  3033. int ret;
  3034. word32 idx = 0;
  3035. RsaKey myKey;
  3036. byte* keyBuf = (byte*)key;
  3037. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  3038. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  3039. (void)ssl;
  3040. (void)cbInfo;
  3041. WOLFSSL_PKMSG("PK RSA PSS SignCheck: sigSz %d, hash %d, mgf %d, keySz %d\n",
  3042. sigSz, hash, mgf, keySz);
  3043. #ifdef TEST_PK_PRIVKEY
  3044. ret = load_key_file(cbInfo->ourKey, &keyBuf, &keySz);
  3045. if (ret != 0)
  3046. return ret;
  3047. #endif
  3048. switch (hash) {
  3049. #ifndef NO_SHA256
  3050. case SHA256h:
  3051. hashType = WC_HASH_TYPE_SHA256;
  3052. break;
  3053. #endif
  3054. #ifdef WOLFSSL_SHA384
  3055. case SHA384h:
  3056. hashType = WC_HASH_TYPE_SHA384;
  3057. break;
  3058. #endif
  3059. #ifdef WOLFSSL_SHA512
  3060. case SHA512h:
  3061. hashType = WC_HASH_TYPE_SHA512;
  3062. break;
  3063. #endif
  3064. }
  3065. ret = wc_InitRsaKey(&myKey, NULL);
  3066. if (ret == 0) {
  3067. ret = wc_RsaPrivateKeyDecode(keyBuf, &idx, &myKey, keySz);
  3068. if (ret == 0) {
  3069. ret = wc_RsaPSS_VerifyInline(sig, sigSz, out, hashType, mgf,
  3070. &myKey);
  3071. }
  3072. wc_FreeRsaKey(&myKey);
  3073. }
  3074. #ifdef TEST_PK_PRIVKEY
  3075. free(keyBuf);
  3076. #endif
  3077. WOLFSSL_PKMSG("PK RSA PSS SignCheck: ret %d\n", ret);
  3078. return ret;
  3079. }
  3080. #endif
  3081. static WC_INLINE int myRsaEnc(WOLFSSL* ssl, const byte* in, word32 inSz,
  3082. byte* out, word32* outSz, const byte* key,
  3083. word32 keySz, void* ctx)
  3084. {
  3085. int ret;
  3086. word32 idx = 0;
  3087. RsaKey myKey;
  3088. WC_RNG rng;
  3089. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  3090. (void)ssl;
  3091. (void)cbInfo;
  3092. WOLFSSL_PKMSG("PK RSA Enc: inSz %d, keySz %d\n", inSz, keySz);
  3093. ret = wc_InitRng(&rng);
  3094. if (ret != 0)
  3095. return ret;
  3096. ret = wc_InitRsaKey(&myKey, NULL);
  3097. if (ret == 0) {
  3098. ret = wc_RsaPublicKeyDecode(key, &idx, &myKey, keySz);
  3099. if (ret == 0) {
  3100. ret = wc_RsaPublicEncrypt(in, inSz, out, *outSz, &myKey, &rng);
  3101. if (ret > 0) {
  3102. *outSz = ret;
  3103. ret = 0; /* reset to success */
  3104. }
  3105. }
  3106. wc_FreeRsaKey(&myKey);
  3107. }
  3108. wc_FreeRng(&rng);
  3109. WOLFSSL_PKMSG("PK RSA Enc: ret %d, outSz %d\n", ret, *outSz);
  3110. return ret;
  3111. }
  3112. static WC_INLINE int myRsaDec(WOLFSSL* ssl, byte* in, word32 inSz,
  3113. byte** out,
  3114. const byte* key, word32 keySz, void* ctx)
  3115. {
  3116. int ret;
  3117. word32 idx = 0;
  3118. RsaKey myKey;
  3119. byte* keyBuf = (byte*)key;
  3120. PkCbInfo* cbInfo = (PkCbInfo*)ctx;
  3121. (void)ssl;
  3122. (void)cbInfo;
  3123. WOLFSSL_PKMSG("PK RSA Dec: inSz %d, keySz %d\n", inSz, keySz);
  3124. #ifdef TEST_PK_PRIVKEY
  3125. ret = load_key_file(cbInfo->ourKey, &keyBuf, &keySz);
  3126. if (ret != 0)
  3127. return ret;
  3128. #endif
  3129. ret = wc_InitRsaKey(&myKey, NULL);
  3130. if (ret == 0) {
  3131. ret = wc_RsaPrivateKeyDecode(keyBuf, &idx, &myKey, keySz);
  3132. if (ret == 0) {
  3133. #ifdef WC_RSA_BLINDING
  3134. ret = wc_RsaSetRNG(&myKey, wolfSSL_GetRNG(ssl));
  3135. if (ret != 0) {
  3136. wc_FreeRsaKey(&myKey);
  3137. return ret;
  3138. }
  3139. #endif
  3140. ret = wc_RsaPrivateDecryptInline(in, inSz, out, &myKey);
  3141. }
  3142. wc_FreeRsaKey(&myKey);
  3143. }
  3144. #ifdef TEST_PK_PRIVKEY
  3145. free(keyBuf);
  3146. #endif
  3147. WOLFSSL_PKMSG("PK RSA Dec: ret %d\n", ret);
  3148. return ret;
  3149. }
  3150. #endif /* NO_RSA */
  3151. static WC_INLINE void SetupPkCallbacks(WOLFSSL_CTX* ctx)
  3152. {
  3153. (void)ctx;
  3154. #ifdef HAVE_ECC
  3155. wolfSSL_CTX_SetEccKeyGenCb(ctx, myEccKeyGen);
  3156. wolfSSL_CTX_SetEccSignCb(ctx, myEccSign);
  3157. wolfSSL_CTX_SetEccVerifyCb(ctx, myEccVerify);
  3158. wolfSSL_CTX_SetEccSharedSecretCb(ctx, myEccSharedSecret);
  3159. #endif /* HAVE_ECC */
  3160. #ifndef NO_DH
  3161. wolfSSL_CTX_SetDhAgreeCb(ctx, myDhCallback);
  3162. #endif
  3163. #ifdef HAVE_ED25519
  3164. wolfSSL_CTX_SetEd25519SignCb(ctx, myEd25519Sign);
  3165. wolfSSL_CTX_SetEd25519VerifyCb(ctx, myEd25519Verify);
  3166. #endif
  3167. #ifdef HAVE_CURVE25519
  3168. wolfSSL_CTX_SetX25519KeyGenCb(ctx, myX25519KeyGen);
  3169. wolfSSL_CTX_SetX25519SharedSecretCb(ctx, myX25519SharedSecret);
  3170. #endif
  3171. #ifdef HAVE_ED448
  3172. wolfSSL_CTX_SetEd448SignCb(ctx, myEd448Sign);
  3173. wolfSSL_CTX_SetEd448VerifyCb(ctx, myEd448Verify);
  3174. #endif
  3175. #ifdef HAVE_CURVE448
  3176. wolfSSL_CTX_SetX448KeyGenCb(ctx, myX448KeyGen);
  3177. wolfSSL_CTX_SetX448SharedSecretCb(ctx, myX448SharedSecret);
  3178. #endif
  3179. #ifndef NO_RSA
  3180. wolfSSL_CTX_SetRsaSignCb(ctx, myRsaSign);
  3181. wolfSSL_CTX_SetRsaVerifyCb(ctx, myRsaVerify);
  3182. wolfSSL_CTX_SetRsaSignCheckCb(ctx, myRsaSignCheck);
  3183. #ifdef WC_RSA_PSS
  3184. wolfSSL_CTX_SetRsaPssSignCb(ctx, myRsaPssSign);
  3185. wolfSSL_CTX_SetRsaPssVerifyCb(ctx, myRsaPssVerify);
  3186. wolfSSL_CTX_SetRsaPssSignCheckCb(ctx, myRsaPssSignCheck);
  3187. #endif
  3188. wolfSSL_CTX_SetRsaEncCb(ctx, myRsaEnc);
  3189. wolfSSL_CTX_SetRsaDecCb(ctx, myRsaDec);
  3190. #endif /* NO_RSA */
  3191. }
  3192. static WC_INLINE void SetupPkCallbackContexts(WOLFSSL* ssl, void* myCtx)
  3193. {
  3194. #ifdef HAVE_ECC
  3195. wolfSSL_SetEccKeyGenCtx(ssl, myCtx);
  3196. wolfSSL_SetEccSignCtx(ssl, myCtx);
  3197. wolfSSL_SetEccVerifyCtx(ssl, myCtx);
  3198. wolfSSL_SetEccSharedSecretCtx(ssl, myCtx);
  3199. #endif /* HAVE_ECC */
  3200. #ifndef NO_DH
  3201. wolfSSL_SetDhAgreeCtx(ssl, myCtx);
  3202. #endif
  3203. #ifdef HAVE_ED25519
  3204. wolfSSL_SetEd25519SignCtx(ssl, myCtx);
  3205. wolfSSL_SetEd25519VerifyCtx(ssl, myCtx);
  3206. #endif
  3207. #ifdef HAVE_CURVE25519
  3208. wolfSSL_SetX25519KeyGenCtx(ssl, myCtx);
  3209. wolfSSL_SetX25519SharedSecretCtx(ssl, myCtx);
  3210. #endif
  3211. #ifdef HAVE_ED448
  3212. wolfSSL_SetEd448SignCtx(ssl, myCtx);
  3213. wolfSSL_SetEd448VerifyCtx(ssl, myCtx);
  3214. #endif
  3215. #ifdef HAVE_CURVE448
  3216. wolfSSL_SetX448KeyGenCtx(ssl, myCtx);
  3217. wolfSSL_SetX448SharedSecretCtx(ssl, myCtx);
  3218. #endif
  3219. #ifndef NO_RSA
  3220. wolfSSL_SetRsaSignCtx(ssl, myCtx);
  3221. wolfSSL_SetRsaVerifyCtx(ssl, myCtx);
  3222. #ifdef WC_RSA_PSS
  3223. wolfSSL_SetRsaPssSignCtx(ssl, myCtx);
  3224. wolfSSL_SetRsaPssVerifyCtx(ssl, myCtx);
  3225. #endif
  3226. wolfSSL_SetRsaEncCtx(ssl, myCtx);
  3227. wolfSSL_SetRsaDecCtx(ssl, myCtx);
  3228. #endif /* NO_RSA */
  3229. }
  3230. #endif /* HAVE_PK_CALLBACKS */
  3231. static WC_INLINE int SimulateWantWriteIOSendCb(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  3232. {
  3233. static int wantWriteFlag = 1;
  3234. int sent;
  3235. int sd = *(int*)ctx;
  3236. (void)ssl;
  3237. if (!wantWriteFlag)
  3238. {
  3239. wantWriteFlag = 1;
  3240. sent = wolfIO_Send(sd, buf, sz, 0);
  3241. if (sent < 0) {
  3242. int err = errno;
  3243. if (err == SOCKET_EWOULDBLOCK || err == SOCKET_EAGAIN) {
  3244. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  3245. }
  3246. else if (err == SOCKET_ECONNRESET) {
  3247. return WOLFSSL_CBIO_ERR_CONN_RST;
  3248. }
  3249. else if (err == SOCKET_EINTR) {
  3250. return WOLFSSL_CBIO_ERR_ISR;
  3251. }
  3252. else if (err == SOCKET_EPIPE) {
  3253. return WOLFSSL_CBIO_ERR_CONN_CLOSE;
  3254. }
  3255. else {
  3256. return WOLFSSL_CBIO_ERR_GENERAL;
  3257. }
  3258. }
  3259. return sent;
  3260. }
  3261. else
  3262. {
  3263. wantWriteFlag = 0;
  3264. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  3265. }
  3266. }
  3267. #if defined(__hpux__) || defined(__MINGW32__) || defined (WOLFSSL_TIRTOS) \
  3268. || defined(_MSC_VER)
  3269. /* HP/UX doesn't have strsep, needed by test/suites.c */
  3270. static WC_INLINE char* strsep(char **stringp, const char *delim)
  3271. {
  3272. char* start;
  3273. char* end;
  3274. start = *stringp;
  3275. if (start == NULL)
  3276. return NULL;
  3277. if ((end = strpbrk(start, delim))) {
  3278. *end++ = '\0';
  3279. *stringp = end;
  3280. } else {
  3281. *stringp = NULL;
  3282. }
  3283. return start;
  3284. }
  3285. #endif /* __hpux__ and others */
  3286. /* Create unique filename, len is length of tempfn name, assuming
  3287. len does not include null terminating character,
  3288. num is number of characters in tempfn name to randomize */
  3289. static WC_INLINE const char* mymktemp(char *tempfn, int len, int num)
  3290. {
  3291. int x, size;
  3292. static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  3293. "abcdefghijklmnopqrstuvwxyz";
  3294. WC_RNG rng;
  3295. byte out;
  3296. if (tempfn == NULL || len < 1 || num < 1 || len <= num) {
  3297. printf("Bad input\n");
  3298. return NULL;
  3299. }
  3300. size = len - 1;
  3301. if (wc_InitRng(&rng) != 0) {
  3302. printf("InitRng failed\n");
  3303. return NULL;
  3304. }
  3305. for (x = size; x > size - num; x--) {
  3306. if (wc_RNG_GenerateBlock(&rng,(byte*)&out, sizeof(out)) != 0) {
  3307. printf("RNG_GenerateBlock failed\n");
  3308. return NULL;
  3309. }
  3310. tempfn[x] = alphanum[out % (sizeof(alphanum) - 1)];
  3311. }
  3312. tempfn[len] = '\0';
  3313. wc_FreeRng(&rng);
  3314. (void)rng; /* for WC_NO_RNG case */
  3315. return tempfn;
  3316. }
  3317. #if defined(HAVE_SESSION_TICKET) && defined(WOLFSSL_NO_DEF_TICKET_ENC_CB) && \
  3318. ((defined(HAVE_CHACHA) && defined(HAVE_POLY1305)) || \
  3319. defined(HAVE_AESGCM))
  3320. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  3321. #include <wolfssl/wolfcrypt/chacha20_poly1305.h>
  3322. #define WOLFSSL_TICKET_KEY_SZ CHACHA20_POLY1305_AEAD_KEYSIZE
  3323. #elif defined(HAVE_AESGCM)
  3324. #include <wolfssl/wolfcrypt/aes.h>
  3325. #include <wolfssl/wolfcrypt/wc_encrypt.h> /* AES IV sizes in FIPS mode */
  3326. #define WOLFSSL_TICKET_KEY_SZ AES_256_KEY_SIZE
  3327. #endif
  3328. typedef struct key_ctx {
  3329. byte name[WOLFSSL_TICKET_NAME_SZ]; /* name for this context */
  3330. byte key[WOLFSSL_TICKET_KEY_SZ]; /* cipher key */
  3331. } key_ctx;
  3332. static THREAD_LS_T key_ctx myKey_ctx;
  3333. static THREAD_LS_T WC_RNG myKey_rng;
  3334. static WC_INLINE int TicketInit(void)
  3335. {
  3336. int ret = wc_InitRng(&myKey_rng);
  3337. if (ret != 0) return ret;
  3338. ret = wc_RNG_GenerateBlock(&myKey_rng, myKey_ctx.key, sizeof(myKey_ctx.key));
  3339. if (ret != 0) return ret;
  3340. ret = wc_RNG_GenerateBlock(&myKey_rng, myKey_ctx.name,sizeof(myKey_ctx.name));
  3341. if (ret != 0) return ret;
  3342. return 0;
  3343. }
  3344. static WC_INLINE void TicketCleanup(void)
  3345. {
  3346. wc_FreeRng(&myKey_rng);
  3347. }
  3348. static WC_INLINE int myTicketEncCb(WOLFSSL* ssl,
  3349. byte key_name[WOLFSSL_TICKET_NAME_SZ],
  3350. byte iv[WOLFSSL_TICKET_IV_SZ],
  3351. byte mac[WOLFSSL_TICKET_MAC_SZ],
  3352. int enc, byte* ticket, int inLen, int* outLen,
  3353. void* userCtx)
  3354. {
  3355. int ret;
  3356. word16 sLen = XHTONS(inLen);
  3357. byte aad[WOLFSSL_TICKET_NAME_SZ + WOLFSSL_TICKET_IV_SZ + 2];
  3358. int aadSz = WOLFSSL_TICKET_NAME_SZ + WOLFSSL_TICKET_IV_SZ + 2;
  3359. byte* tmp = aad;
  3360. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  3361. /* chahca20/poly1305 */
  3362. #elif defined(HAVE_AESGCM)
  3363. Aes aes;
  3364. #endif
  3365. (void)ssl;
  3366. (void)userCtx;
  3367. /* encrypt */
  3368. if (enc) {
  3369. XMEMCPY(key_name, myKey_ctx.name, WOLFSSL_TICKET_NAME_SZ);
  3370. ret = wc_RNG_GenerateBlock(&myKey_rng, iv, WOLFSSL_TICKET_IV_SZ);
  3371. if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
  3372. /* build aad from key name, iv, and length */
  3373. XMEMCPY(tmp, key_name, WOLFSSL_TICKET_NAME_SZ);
  3374. tmp += WOLFSSL_TICKET_NAME_SZ;
  3375. XMEMCPY(tmp, iv, WOLFSSL_TICKET_IV_SZ);
  3376. tmp += WOLFSSL_TICKET_IV_SZ;
  3377. XMEMCPY(tmp, &sLen, sizeof(sLen));
  3378. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  3379. ret = wc_ChaCha20Poly1305_Encrypt(myKey_ctx.key, iv,
  3380. aad, aadSz,
  3381. ticket, inLen,
  3382. ticket,
  3383. mac);
  3384. #elif defined(HAVE_AESGCM)
  3385. ret = wc_AesInit(&aes, NULL, INVALID_DEVID);
  3386. if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
  3387. ret = wc_AesGcmSetKey(&aes, myKey_ctx.key, sizeof(myKey_ctx.key));
  3388. if (ret == 0) {
  3389. ret = wc_AesGcmEncrypt(&aes, ticket, ticket, inLen,
  3390. iv, GCM_NONCE_MID_SZ, mac, AES_BLOCK_SIZE,
  3391. aad, aadSz);
  3392. }
  3393. wc_AesFree(&aes);
  3394. #endif
  3395. if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
  3396. *outLen = inLen; /* no padding in this mode */
  3397. }
  3398. /* decrypt */
  3399. else {
  3400. /* see if we know this key */
  3401. if (XMEMCMP(key_name, myKey_ctx.name, WOLFSSL_TICKET_NAME_SZ) != 0){
  3402. printf("client presented unknown ticket key name %s\n", key_name);
  3403. return WOLFSSL_TICKET_RET_FATAL;
  3404. }
  3405. /* build aad from key name, iv, and length */
  3406. XMEMCPY(tmp, key_name, WOLFSSL_TICKET_NAME_SZ);
  3407. tmp += WOLFSSL_TICKET_NAME_SZ;
  3408. XMEMCPY(tmp, iv, WOLFSSL_TICKET_IV_SZ);
  3409. tmp += WOLFSSL_TICKET_IV_SZ;
  3410. XMEMCPY(tmp, &sLen, sizeof(sLen));
  3411. #if defined(HAVE_CHACHA) && defined(HAVE_POLY1305)
  3412. ret = wc_ChaCha20Poly1305_Decrypt(myKey_ctx.key, iv,
  3413. aad, aadSz,
  3414. ticket, inLen,
  3415. mac,
  3416. ticket);
  3417. #elif defined(HAVE_AESGCM)
  3418. ret = wc_AesInit(&aes, NULL, INVALID_DEVID);
  3419. if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
  3420. ret = wc_AesGcmSetKey(&aes, myKey_ctx.key, sizeof(myKey_ctx.key));
  3421. if (ret == 0) {
  3422. ret = wc_AesGcmDecrypt(&aes, ticket, ticket, inLen,
  3423. iv, GCM_NONCE_MID_SZ, mac, AES_BLOCK_SIZE,
  3424. aad, aadSz);
  3425. }
  3426. wc_AesFree(&aes);
  3427. #endif
  3428. if (ret != 0) return WOLFSSL_TICKET_RET_REJECT;
  3429. *outLen = inLen; /* no padding in this mode */
  3430. }
  3431. return WOLFSSL_TICKET_RET_OK;
  3432. }
  3433. #endif /* HAVE_SESSION_TICKET && ((HAVE_CHACHA && HAVE_POLY1305) || HAVE_AESGCM) */
  3434. static WC_INLINE word16 GetRandomPort(void)
  3435. {
  3436. word16 port = 0;
  3437. /* Generate random port for testing */
  3438. WC_RNG rng;
  3439. if (wc_InitRng(&rng) == 0) {
  3440. if (wc_RNG_GenerateBlock(&rng, (byte*)&port, sizeof(port)) == 0) {
  3441. port |= 0xC000; /* Make sure its in the 49152 - 65535 range */
  3442. }
  3443. wc_FreeRng(&rng);
  3444. }
  3445. (void)rng; /* for WC_NO_RNG case */
  3446. return port;
  3447. }
  3448. #ifdef WOLFSSL_EARLY_DATA
  3449. static WC_INLINE void EarlyDataStatus(WOLFSSL* ssl)
  3450. {
  3451. int earlyData_status;
  3452. #ifdef OPENSSL_EXTRA
  3453. earlyData_status = SSL_get_early_data_status(ssl);
  3454. #else
  3455. earlyData_status = wolfSSL_get_early_data_status(ssl);
  3456. #endif
  3457. if (earlyData_status < 0) return;
  3458. printf("Early Data was ");
  3459. switch(earlyData_status) {
  3460. case WOLFSSL_EARLY_DATA_NOT_SENT:
  3461. printf("not sent.\n");
  3462. break;
  3463. case WOLFSSL_EARLY_DATA_REJECTED:
  3464. printf("rejected.\n");
  3465. break;
  3466. case WOLFSSL_EARLY_DATA_ACCEPTED:
  3467. printf("accepted\n");
  3468. break;
  3469. default:
  3470. printf("unknown...\n");
  3471. }
  3472. }
  3473. #endif /* WOLFSSL_EARLY_DATA */
  3474. #endif /* wolfSSL_TEST_H */