test.h 160 KB

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