test.h 147 KB

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