test.h 159 KB

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