test.h 154 KB

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