test.h 118 KB

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