test.h 135 KB

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