test.h 136 KB

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