test.h 163 KB

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