random.c 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836
  1. /* random.c
  2. *
  3. * Copyright (C) 2006-2023 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. /*
  22. DESCRIPTION
  23. This library contains implementation for the random number generator.
  24. */
  25. #ifdef HAVE_CONFIG_H
  26. #include <config.h>
  27. #endif
  28. #include <wolfssl/wolfcrypt/settings.h>
  29. #include <wolfssl/wolfcrypt/error-crypt.h>
  30. /* on HPUX 11 you may need to install /dev/random see
  31. http://h20293.www2.hp.com/portal/swdepot/displayProductInfo.do?productNumber=KRNG11I
  32. */
  33. #if defined(ESP_IDF_VERSION_MAJOR) && ESP_IDF_VERSION_MAJOR >= 5
  34. #include <esp_random.h>
  35. #endif
  36. #if defined(HAVE_FIPS) && \
  37. defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)
  38. /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */
  39. #define FIPS_NO_WRAPPERS
  40. #ifdef USE_WINDOWS_API
  41. #pragma code_seg(".fipsA$c")
  42. #pragma const_seg(".fipsB$c")
  43. #endif
  44. #endif
  45. #include <wolfssl/wolfcrypt/random.h>
  46. #include <wolfssl/wolfcrypt/cpuid.h>
  47. #ifdef HAVE_ENTROPY_MEMUSE
  48. #include <wolfssl/wolfcrypt/sha3.h>
  49. #if defined(__APPLE__) || defined(__MACH__)
  50. #include <mach/mach_time.h>
  51. #endif
  52. #endif
  53. /* If building for old FIPS. */
  54. #if defined(HAVE_FIPS) && \
  55. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2))
  56. int wc_GenerateSeed(OS_Seed* os, byte* seed, word32 sz)
  57. {
  58. return GenerateSeed(os, seed, sz);
  59. }
  60. int wc_InitRng_ex(WC_RNG* rng, void* heap, int devId)
  61. {
  62. (void)heap;
  63. (void)devId;
  64. return InitRng_fips(rng);
  65. }
  66. WOLFSSL_ABI
  67. int wc_InitRng(WC_RNG* rng)
  68. {
  69. return InitRng_fips(rng);
  70. }
  71. int wc_RNG_GenerateBlock(WC_RNG* rng, byte* b, word32 sz)
  72. {
  73. return RNG_GenerateBlock_fips(rng, b, sz);
  74. }
  75. int wc_RNG_GenerateByte(WC_RNG* rng, byte* b)
  76. {
  77. return RNG_GenerateByte(rng, b);
  78. }
  79. #ifdef HAVE_HASHDRBG
  80. int wc_FreeRng(WC_RNG* rng)
  81. {
  82. return FreeRng_fips(rng);
  83. }
  84. int wc_RNG_HealthTest(int reseed, const byte* seedA, word32 seedASz,
  85. const byte* seedB, word32 seedBSz,
  86. byte* output, word32 outputSz)
  87. {
  88. return RNG_HealthTest_fips(reseed, seedA, seedASz,
  89. seedB, seedBSz, output, outputSz);
  90. }
  91. #endif /* HAVE_HASHDRBG */
  92. #else /* else build without fips, or for new fips */
  93. #ifndef WC_NO_RNG /* if not FIPS and RNG is disabled then do not compile */
  94. #include <wolfssl/wolfcrypt/sha256.h>
  95. #ifdef WOLF_CRYPTO_CB
  96. #include <wolfssl/wolfcrypt/cryptocb.h>
  97. #endif
  98. #ifdef NO_INLINE
  99. #include <wolfssl/wolfcrypt/misc.h>
  100. #else
  101. #define WOLFSSL_MISC_INCLUDED
  102. #include <wolfcrypt/src/misc.c>
  103. #endif
  104. #if defined(WOLFSSL_SGX)
  105. #include <sgx_trts.h>
  106. #elif defined(USE_WINDOWS_API)
  107. #ifndef _WIN32_WINNT
  108. #define _WIN32_WINNT 0x0400
  109. #endif
  110. #include <windows.h>
  111. #include <wincrypt.h>
  112. #elif defined(HAVE_WNR)
  113. #include <wnr.h>
  114. #include <wolfssl/wolfcrypt/logging.h>
  115. wolfSSL_Mutex wnr_mutex; /* global netRandom mutex */
  116. int wnr_timeout = 0; /* entropy timeout, milliseconds */
  117. int wnr_mutex_init = 0; /* flag for mutex init */
  118. wnr_context* wnr_ctx; /* global netRandom context */
  119. #elif defined(FREESCALE_KSDK_2_0_TRNG)
  120. #include "fsl_trng.h"
  121. #elif defined(FREESCALE_KSDK_2_0_RNGA)
  122. #include "fsl_rnga.h"
  123. #elif defined(WOLFSSL_WICED)
  124. #include "wiced_crypto.h"
  125. #elif defined(WOLFSSL_NETBURNER)
  126. #include <predef.h>
  127. #include <basictypes.h>
  128. #include <random.h>
  129. #elif defined(WOLFSSL_XILINX_CRYPT_VERSAL)
  130. #include "wolfssl/wolfcrypt/port/xilinx/xil-versal-trng.h"
  131. #elif defined(NO_DEV_RANDOM)
  132. #elif defined(CUSTOM_RAND_GENERATE)
  133. #elif defined(CUSTOM_RAND_GENERATE_BLOCK)
  134. #elif defined(CUSTOM_RAND_GENERATE_SEED)
  135. #elif defined(WOLFSSL_GENSEED_FORTEST)
  136. #elif defined(WOLFSSL_MDK_ARM)
  137. #elif defined(WOLFSSL_IAR_ARM)
  138. #elif defined(WOLFSSL_ROWLEY_ARM)
  139. #elif defined(WOLFSSL_EMBOS)
  140. #elif defined(WOLFSSL_DEOS)
  141. #elif defined(MICRIUM)
  142. #elif defined(WOLFSSL_NUCLEUS)
  143. #elif defined(WOLFSSL_PB)
  144. #elif defined(WOLFSSL_ZEPHYR)
  145. #elif defined(WOLFSSL_TELIT_M2MB)
  146. #elif defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_TRNG)
  147. #elif defined(WOLFSSL_IMXRT1170_CAAM)
  148. #elif defined(WOLFSSL_GETRANDOM)
  149. #include <errno.h>
  150. #include <sys/random.h>
  151. #else
  152. /* include headers that may be needed to get good seed */
  153. #include <fcntl.h>
  154. #ifndef EBSNET
  155. #include <unistd.h>
  156. #endif
  157. #endif
  158. #if defined(WOLFSSL_SILABS_SE_ACCEL)
  159. #include <wolfssl/wolfcrypt/port/silabs/silabs_random.h>
  160. #endif
  161. #if defined(WOLFSSL_IOTSAFE) && defined(HAVE_IOTSAFE_HWRNG)
  162. #include <wolfssl/wolfcrypt/port/iotsafe/iotsafe.h>
  163. #endif
  164. #if defined(WOLFSSL_HAVE_PSA) && !defined(WOLFSSL_PSA_NO_RNG)
  165. #include <wolfssl/wolfcrypt/port/psa/psa.h>
  166. #endif
  167. #if defined(HAVE_INTEL_RDRAND) || defined(HAVE_INTEL_RDSEED) || \
  168. defined(HAVE_AMD_RDSEED)
  169. static word32 intel_flags = 0;
  170. static void wc_InitRng_IntelRD(void)
  171. {
  172. intel_flags = cpuid_get_flags();
  173. }
  174. #if (defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED)) && \
  175. !defined(WOLFSSL_LINUXKM)
  176. static int wc_GenerateSeed_IntelRD(OS_Seed* os, byte* output, word32 sz);
  177. #endif
  178. #ifdef HAVE_INTEL_RDRAND
  179. static int wc_GenerateRand_IntelRD(OS_Seed* os, byte* output, word32 sz);
  180. #endif
  181. #ifdef USE_WINDOWS_API
  182. #define USE_INTEL_INTRINSICS
  183. #elif !defined __GNUC__ || defined __clang__ || __GNUC__ > 4
  184. #define USE_INTEL_INTRINSICS
  185. #else
  186. #undef USE_INTEL_INTRINSICS
  187. #endif
  188. #ifdef USE_INTEL_INTRINSICS
  189. #include <immintrin.h>
  190. /* Before clang 7 or GCC 9, immintrin.h did not define _rdseed64_step() */
  191. #ifndef HAVE_INTEL_RDSEED
  192. #elif defined __clang__ && __clang_major__ > 6
  193. #elif !defined __GNUC__
  194. #elif __GNUC__ > 8
  195. #else
  196. #ifndef __clang__
  197. #pragma GCC push_options
  198. #pragma GCC target("rdseed")
  199. #else
  200. #define __RDSEED__
  201. #endif
  202. #include <x86intrin.h>
  203. #ifndef __clang__
  204. #pragma GCC pop_options
  205. #endif
  206. #endif
  207. #endif /* USE_WINDOWS_API */
  208. #endif
  209. /* Start NIST DRBG code */
  210. #ifdef HAVE_HASHDRBG
  211. #define OUTPUT_BLOCK_LEN (WC_SHA256_DIGEST_SIZE)
  212. #define MAX_REQUEST_LEN (0x10000)
  213. #define RESEED_INTERVAL WC_RESEED_INTERVAL
  214. /* The security strength for the RNG is the target number of bits of
  215. * entropy you are looking for in a seed. */
  216. #ifndef RNG_SECURITY_STRENGTH
  217. /* SHA-256 requires a minimum of 256-bits of entropy. */
  218. #define RNG_SECURITY_STRENGTH (256)
  219. #endif
  220. #ifndef ENTROPY_SCALE_FACTOR
  221. /* The entropy scale factor should be the whole number inverse of the
  222. * minimum bits of entropy per bit of NDRNG output. */
  223. #if defined(HAVE_ENTROPY_MEMUSE)
  224. /* Full strength, conditioned entropy is requested of MemUse Entropy. */
  225. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  226. (HAVE_FIPS_VERSION >= 2)
  227. #define ENTROPY_SCALE_FACTOR (4)
  228. #else
  229. #define ENTROPY_SCALE_FACTOR (1)
  230. #endif
  231. #elif defined(HAVE_AMD_RDSEED)
  232. /* This will yield a SEED_SZ of 16kb. Since nonceSz will be 0,
  233. * we'll add an additional 8kb on top. */
  234. #define ENTROPY_SCALE_FACTOR (512)
  235. #elif defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND)
  236. /* The value of 2 applies to Intel's RDSEED which provides about
  237. * 0.5 bits minimum of entropy per bit. The value of 4 gives a
  238. * conservative margin for FIPS. */
  239. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  240. (HAVE_FIPS_VERSION >= 2)
  241. #define ENTROPY_SCALE_FACTOR (2*4)
  242. #else
  243. /* Not FIPS, but Intel RDSEED, only double. */
  244. #define ENTROPY_SCALE_FACTOR (2)
  245. #endif
  246. #elif defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  247. (HAVE_FIPS_VERSION >= 2)
  248. /* If doing a FIPS build without a specific scale factor, default
  249. * to 4. This will give 1024 bits of entropy. More is better, but
  250. * more is also slower. */
  251. #define ENTROPY_SCALE_FACTOR (4)
  252. #else
  253. /* Setting the default to 1. */
  254. #define ENTROPY_SCALE_FACTOR (1)
  255. #endif
  256. #endif
  257. #ifndef SEED_BLOCK_SZ
  258. /* The seed block size, is the size of the output of the underlying NDRNG.
  259. * This value is used for testing the output of the NDRNG. */
  260. #if defined(HAVE_AMD_RDSEED)
  261. /* AMD's RDSEED instruction works in 128-bit blocks read 64-bits
  262. * at a time. */
  263. #define SEED_BLOCK_SZ (sizeof(word64)*2)
  264. #elif defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND)
  265. /* RDSEED outputs in blocks of 64-bits. */
  266. #define SEED_BLOCK_SZ sizeof(word64)
  267. #else
  268. /* Setting the default to 4. */
  269. #define SEED_BLOCK_SZ 4
  270. #endif
  271. #endif
  272. #define SEED_SZ (RNG_SECURITY_STRENGTH*ENTROPY_SCALE_FACTOR/8)
  273. /* The maximum seed size will be the seed size plus a seed block for the
  274. * test, and an additional half of the seed size. This additional half
  275. * is in case the user does not supply a nonce. A nonce will be obtained
  276. * from the NDRNG. */
  277. #define MAX_SEED_SZ (SEED_SZ + SEED_SZ/2 + SEED_BLOCK_SZ)
  278. #ifdef WC_RNG_SEED_CB
  279. static wc_RngSeed_Cb seedCb = NULL;
  280. int wc_SetSeed_Cb(wc_RngSeed_Cb cb)
  281. {
  282. seedCb = cb;
  283. return 0;
  284. }
  285. #endif
  286. /* Internal return codes */
  287. #define DRBG_SUCCESS 0
  288. #define DRBG_FAILURE 1
  289. #define DRBG_NEED_RESEED 2
  290. #define DRBG_CONT_FAILURE 3
  291. #define DRBG_NO_SEED_CB 4
  292. /* RNG health states */
  293. #define DRBG_NOT_INIT 0
  294. #define DRBG_OK 1
  295. #define DRBG_FAILED 2
  296. #define DRBG_CONT_FAILED 3
  297. #define RNG_HEALTH_TEST_CHECK_SIZE (WC_SHA256_DIGEST_SIZE * 4)
  298. /* Verify max gen block len */
  299. #if RNG_MAX_BLOCK_LEN > MAX_REQUEST_LEN
  300. #error RNG_MAX_BLOCK_LEN is larger than NIST DBRG max request length
  301. #endif
  302. enum {
  303. drbgInitC = 0,
  304. drbgReseed = 1,
  305. drbgGenerateW = 2,
  306. drbgGenerateH = 3,
  307. drbgInitV = 4
  308. };
  309. typedef struct DRBG_internal DRBG_internal;
  310. static int wc_RNG_HealthTestLocal(int reseed);
  311. /* Hash Derivation Function */
  312. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  313. static int Hash_df(DRBG_internal* drbg, byte* out, word32 outSz, byte type,
  314. const byte* inA, word32 inASz,
  315. const byte* inB, word32 inBSz)
  316. {
  317. int ret = DRBG_FAILURE;
  318. byte ctr;
  319. word32 i;
  320. word32 len;
  321. word32 bits = (outSz * 8); /* reverse byte order */
  322. #ifdef WOLFSSL_SMALL_STACK_CACHE
  323. wc_Sha256* sha = &drbg->sha256;
  324. #else
  325. wc_Sha256 sha[1];
  326. #endif
  327. #ifdef WOLFSSL_SMALL_STACK
  328. byte* digest;
  329. #else
  330. byte digest[WC_SHA256_DIGEST_SIZE];
  331. #endif
  332. if (drbg == NULL) {
  333. return DRBG_FAILURE;
  334. }
  335. #ifdef WOLFSSL_SMALL_STACK
  336. digest = (byte*)XMALLOC(WC_SHA256_DIGEST_SIZE, drbg->heap,
  337. DYNAMIC_TYPE_DIGEST);
  338. if (digest == NULL)
  339. return DRBG_FAILURE;
  340. #endif
  341. #ifdef LITTLE_ENDIAN_ORDER
  342. bits = ByteReverseWord32(bits);
  343. #endif
  344. len = (outSz / OUTPUT_BLOCK_LEN)
  345. + ((outSz % OUTPUT_BLOCK_LEN) ? 1 : 0);
  346. ctr = 1;
  347. for (i = 0; i < len; i++) {
  348. #ifndef WOLFSSL_SMALL_STACK_CACHE
  349. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
  350. ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId);
  351. #else
  352. ret = wc_InitSha256(sha);
  353. #endif
  354. if (ret != 0)
  355. break;
  356. #endif
  357. ret = wc_Sha256Update(sha, &ctr, sizeof(ctr));
  358. if (ret == 0) {
  359. ctr++;
  360. ret = wc_Sha256Update(sha, (byte*)&bits, sizeof(bits));
  361. }
  362. if (ret == 0) {
  363. /* churning V is the only string that doesn't have the type added */
  364. if (type != drbgInitV)
  365. ret = wc_Sha256Update(sha, &type, sizeof(type));
  366. }
  367. if (ret == 0)
  368. ret = wc_Sha256Update(sha, inA, inASz);
  369. if (ret == 0) {
  370. if (inB != NULL && inBSz > 0)
  371. ret = wc_Sha256Update(sha, inB, inBSz);
  372. }
  373. if (ret == 0)
  374. ret = wc_Sha256Final(sha, digest);
  375. #ifndef WOLFSSL_SMALL_STACK_CACHE
  376. wc_Sha256Free(sha);
  377. #endif
  378. if (ret == 0) {
  379. if (outSz > OUTPUT_BLOCK_LEN) {
  380. XMEMCPY(out, digest, OUTPUT_BLOCK_LEN);
  381. outSz -= OUTPUT_BLOCK_LEN;
  382. out += OUTPUT_BLOCK_LEN;
  383. }
  384. else {
  385. XMEMCPY(out, digest, outSz);
  386. }
  387. }
  388. }
  389. ForceZero(digest, WC_SHA256_DIGEST_SIZE);
  390. #ifdef WOLFSSL_SMALL_STACK
  391. XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST);
  392. #endif
  393. return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
  394. }
  395. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  396. static int Hash_DRBG_Reseed(DRBG_internal* drbg, const byte* seed, word32 seedSz)
  397. {
  398. int ret;
  399. #ifdef WOLFSSL_SMALL_STACK
  400. byte* newV;
  401. #else
  402. byte newV[DRBG_SEED_LEN];
  403. #endif
  404. if (drbg == NULL) {
  405. return DRBG_FAILURE;
  406. }
  407. #ifdef WOLFSSL_SMALL_STACK
  408. newV = (byte*)XMALLOC(DRBG_SEED_LEN, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER);
  409. if (newV == NULL) {
  410. return MEMORY_E;
  411. }
  412. #endif
  413. XMEMSET(newV, 0, DRBG_SEED_LEN);
  414. ret = Hash_df(drbg, newV, DRBG_SEED_LEN, drbgReseed,
  415. drbg->V, sizeof(drbg->V), seed, seedSz);
  416. if (ret == DRBG_SUCCESS) {
  417. XMEMCPY(drbg->V, newV, sizeof(drbg->V));
  418. ForceZero(newV, DRBG_SEED_LEN);
  419. ret = Hash_df(drbg, drbg->C, sizeof(drbg->C), drbgInitC, drbg->V,
  420. sizeof(drbg->V), NULL, 0);
  421. }
  422. if (ret == DRBG_SUCCESS) {
  423. drbg->reseedCtr = 1;
  424. }
  425. #ifdef WOLFSSL_SMALL_STACK
  426. XFREE(newV, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER);
  427. #endif
  428. return ret;
  429. }
  430. /* Returns: DRBG_SUCCESS and DRBG_FAILURE or BAD_FUNC_ARG on fail */
  431. int wc_RNG_DRBG_Reseed(WC_RNG* rng, const byte* seed, word32 seedSz)
  432. {
  433. if (rng == NULL || seed == NULL) {
  434. return BAD_FUNC_ARG;
  435. }
  436. if (rng->drbg == NULL) {
  437. #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND)
  438. if (IS_INTEL_RDRAND(intel_flags)) {
  439. /* using RDRAND not DRBG, so return success */
  440. return 0;
  441. }
  442. return BAD_FUNC_ARG;
  443. #endif
  444. }
  445. return Hash_DRBG_Reseed((DRBG_internal *)rng->drbg, seed, seedSz);
  446. }
  447. static WC_INLINE void array_add_one(byte* data, word32 dataSz)
  448. {
  449. int i;
  450. for (i = (int)dataSz - 1; i >= 0; i--) {
  451. data[i]++;
  452. if (data[i] != 0) break;
  453. }
  454. }
  455. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  456. static int Hash_gen(DRBG_internal* drbg, byte* out, word32 outSz, const byte* V)
  457. {
  458. int ret = DRBG_FAILURE;
  459. #ifdef WOLFSSL_SMALL_STACK
  460. byte* data;
  461. byte* digest;
  462. #else
  463. byte data[DRBG_SEED_LEN];
  464. byte digest[WC_SHA256_DIGEST_SIZE];
  465. #endif
  466. word32 i;
  467. word32 len;
  468. #ifdef WOLFSSL_SMALL_STACK_CACHE
  469. wc_Sha256* sha = &drbg->sha256;
  470. #else
  471. wc_Sha256 sha[1];
  472. #endif
  473. if (drbg == NULL) {
  474. return DRBG_FAILURE;
  475. }
  476. #ifdef WOLFSSL_SMALL_STACK
  477. data = (byte*)XMALLOC(DRBG_SEED_LEN, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER);
  478. digest = (byte*)XMALLOC(WC_SHA256_DIGEST_SIZE, drbg->heap,
  479. DYNAMIC_TYPE_DIGEST);
  480. if (data == NULL || digest == NULL) {
  481. XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST);
  482. XFREE(data, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER);
  483. return DRBG_FAILURE;
  484. }
  485. #endif
  486. /* Special case: outSz is 0 and out is NULL. wc_Generate a block to save for
  487. * the continuous test. */
  488. if (outSz == 0) {
  489. outSz = 1;
  490. }
  491. len = (outSz / OUTPUT_BLOCK_LEN) + ((outSz % OUTPUT_BLOCK_LEN) ? 1 : 0);
  492. XMEMCPY(data, V, DRBG_SEED_LEN);
  493. for (i = 0; i < len; i++) {
  494. #ifndef WOLFSSL_SMALL_STACK_CACHE
  495. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
  496. ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId);
  497. #else
  498. ret = wc_InitSha256(sha);
  499. #endif
  500. if (ret == 0)
  501. #endif
  502. ret = wc_Sha256Update(sha, data, DRBG_SEED_LEN);
  503. if (ret == 0)
  504. ret = wc_Sha256Final(sha, digest);
  505. #ifndef WOLFSSL_SMALL_STACK_CACHE
  506. wc_Sha256Free(sha);
  507. #endif
  508. if (ret == 0) {
  509. if (out != NULL && outSz != 0) {
  510. if (outSz >= OUTPUT_BLOCK_LEN) {
  511. XMEMCPY(out, digest, OUTPUT_BLOCK_LEN);
  512. outSz -= OUTPUT_BLOCK_LEN;
  513. out += OUTPUT_BLOCK_LEN;
  514. array_add_one(data, DRBG_SEED_LEN);
  515. }
  516. else {
  517. XMEMCPY(out, digest, outSz);
  518. outSz = 0;
  519. }
  520. }
  521. }
  522. else {
  523. /* wc_Sha256Update or wc_Sha256Final returned error */
  524. break;
  525. }
  526. }
  527. ForceZero(data, DRBG_SEED_LEN);
  528. #ifdef WOLFSSL_SMALL_STACK
  529. XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST);
  530. XFREE(data, drbg->heap, DYNAMIC_TYPE_TMP_BUFFER);
  531. #endif
  532. return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
  533. }
  534. static WC_INLINE void array_add(byte* d, word32 dLen, const byte* s, word32 sLen)
  535. {
  536. if (dLen > 0 && sLen > 0 && dLen >= sLen) {
  537. int sIdx, dIdx;
  538. word16 carry = 0;
  539. dIdx = (int)dLen - 1;
  540. for (sIdx = (int)sLen - 1; sIdx >= 0; sIdx--) {
  541. carry += (word16)(d[dIdx] + s[sIdx]);
  542. d[dIdx] = (byte)carry;
  543. carry >>= 8;
  544. dIdx--;
  545. }
  546. for (; dIdx >= 0; dIdx--) {
  547. carry += (word16)d[dIdx];
  548. d[dIdx] = (byte)carry;
  549. carry >>= 8;
  550. }
  551. }
  552. }
  553. /* Returns: DRBG_SUCCESS, DRBG_NEED_RESEED, or DRBG_FAILURE */
  554. static int Hash_DRBG_Generate(DRBG_internal* drbg, byte* out, word32 outSz)
  555. {
  556. int ret;
  557. #ifdef WOLFSSL_SMALL_STACK_CACHE
  558. wc_Sha256* sha = &drbg->sha256;
  559. #else
  560. wc_Sha256 sha[1];
  561. #endif
  562. byte type;
  563. word32 reseedCtr;
  564. if (drbg == NULL) {
  565. return DRBG_FAILURE;
  566. }
  567. if (drbg->reseedCtr == RESEED_INTERVAL) {
  568. return DRBG_NEED_RESEED;
  569. }
  570. else {
  571. #ifndef WOLFSSL_SMALL_STACK
  572. byte digest[WC_SHA256_DIGEST_SIZE];
  573. #else
  574. byte* digest = (byte*)XMALLOC(WC_SHA256_DIGEST_SIZE, drbg->heap,
  575. DYNAMIC_TYPE_DIGEST);
  576. if (digest == NULL)
  577. return DRBG_FAILURE;
  578. #endif
  579. type = drbgGenerateH;
  580. reseedCtr = drbg->reseedCtr;
  581. ret = Hash_gen(drbg, out, outSz, drbg->V);
  582. if (ret == DRBG_SUCCESS) {
  583. #ifndef WOLFSSL_SMALL_STACK_CACHE
  584. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
  585. ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId);
  586. #else
  587. ret = wc_InitSha256(sha);
  588. #endif
  589. if (ret == 0)
  590. #endif
  591. ret = wc_Sha256Update(sha, &type, sizeof(type));
  592. if (ret == 0)
  593. ret = wc_Sha256Update(sha, drbg->V, sizeof(drbg->V));
  594. if (ret == 0)
  595. ret = wc_Sha256Final(sha, digest);
  596. #ifndef WOLFSSL_SMALL_STACK_CACHE
  597. wc_Sha256Free(sha);
  598. #endif
  599. if (ret == 0) {
  600. array_add(drbg->V, sizeof(drbg->V), digest, WC_SHA256_DIGEST_SIZE);
  601. array_add(drbg->V, sizeof(drbg->V), drbg->C, sizeof(drbg->C));
  602. #ifdef LITTLE_ENDIAN_ORDER
  603. reseedCtr = ByteReverseWord32(reseedCtr);
  604. #endif
  605. array_add(drbg->V, sizeof(drbg->V),
  606. (byte*)&reseedCtr, sizeof(reseedCtr));
  607. ret = DRBG_SUCCESS;
  608. }
  609. drbg->reseedCtr++;
  610. }
  611. ForceZero(digest, WC_SHA256_DIGEST_SIZE);
  612. #ifdef WOLFSSL_SMALL_STACK
  613. XFREE(digest, drbg->heap, DYNAMIC_TYPE_DIGEST);
  614. #endif
  615. }
  616. return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
  617. }
  618. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  619. static int Hash_DRBG_Instantiate(DRBG_internal* drbg, const byte* seed, word32 seedSz,
  620. const byte* nonce, word32 nonceSz,
  621. void* heap, int devId)
  622. {
  623. int ret = DRBG_FAILURE;
  624. XMEMSET(drbg, 0, sizeof(DRBG_internal));
  625. drbg->heap = heap;
  626. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
  627. drbg->devId = devId;
  628. #else
  629. (void)devId;
  630. #endif
  631. #ifdef WOLFSSL_SMALL_STACK_CACHE
  632. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
  633. ret = wc_InitSha256_ex(&drbg->sha256, drbg->heap, drbg->devId);
  634. #else
  635. ret = wc_InitSha256(&drbg->sha256);
  636. #endif
  637. if (ret != 0)
  638. return ret;
  639. #endif
  640. if (Hash_df(drbg, drbg->V, sizeof(drbg->V), drbgInitV, seed, seedSz,
  641. nonce, nonceSz) == DRBG_SUCCESS &&
  642. Hash_df(drbg, drbg->C, sizeof(drbg->C), drbgInitC, drbg->V,
  643. sizeof(drbg->V), NULL, 0) == DRBG_SUCCESS) {
  644. drbg->reseedCtr = 1;
  645. ret = DRBG_SUCCESS;
  646. }
  647. return ret;
  648. }
  649. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  650. static int Hash_DRBG_Uninstantiate(DRBG_internal* drbg)
  651. {
  652. word32 i;
  653. int compareSum = 0;
  654. byte* compareDrbg = (byte*)drbg;
  655. #ifdef WOLFSSL_SMALL_STACK_CACHE
  656. wc_Sha256Free(&drbg->sha256);
  657. #endif
  658. ForceZero(drbg, sizeof(DRBG_internal));
  659. for (i = 0; i < sizeof(DRBG_internal); i++) {
  660. compareSum |= compareDrbg[i] ^ 0;
  661. }
  662. return (compareSum == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
  663. }
  664. int wc_RNG_TestSeed(const byte* seed, word32 seedSz)
  665. {
  666. int ret = 0;
  667. /* Check the seed for duplicate words. */
  668. word32 seedIdx = 0;
  669. word32 scratchSz = min(SEED_BLOCK_SZ, seedSz - SEED_BLOCK_SZ);
  670. while (seedIdx < seedSz - SEED_BLOCK_SZ) {
  671. if (ConstantCompare(seed + seedIdx,
  672. seed + seedIdx + scratchSz,
  673. (int)scratchSz) == 0) {
  674. ret = DRBG_CONT_FAILURE;
  675. }
  676. seedIdx += SEED_BLOCK_SZ;
  677. scratchSz = min(SEED_BLOCK_SZ, (seedSz - seedIdx));
  678. }
  679. return ret;
  680. }
  681. #endif /* HAVE_HASHDRBG */
  682. /* End NIST DRBG Code */
  683. #ifdef HAVE_ENTROPY_MEMUSE
  684. /* Define ENTROPY_MEMUSE_THREAD to force use of counter in a new thread.
  685. * Only do this when high resolution timer not otherwise available.
  686. */
  687. /* Number of bytes that will hold the maximum entropy bits. */
  688. #define MAX_ENTROPY_BYTES (MAX_ENTROPY_BITS / 8)
  689. /* Number of bits stored for one sample. */
  690. #define ENTROPY_BITS_USED 8
  691. /* Minimum entropy from a sample. */
  692. #define ENTROPY_MIN 1
  693. /* Number of extra samples to ensure full entropy. */
  694. #define ENTROPY_EXTRA 64
  695. /* Maximum number of bytes to sample to produce max entropy. */
  696. #define MAX_NOISE_CNT (MAX_ENTROPY_BITS * 8 + ENTROPY_EXTRA)
  697. /* MemUse entropy global state initialized. */
  698. static int entropy_memuse_initialized = 0;
  699. /* Global SHA-3 object used for conditioning entropy and creating noise. */
  700. static wc_Sha3 entropyHash;
  701. /* Reset the health tests. */
  702. static void Entropy_HealthTest_Reset(void);
  703. #if !defined(ENTROPY_MEMUSE_THREAD) && \
  704. (defined(__x86_64__) || defined(__i386__))
  705. /* Get the high resolution time counter.
  706. *
  707. * @return 64-bit count of CPU cycles.
  708. */
  709. static WC_INLINE word64 Entropy_TimeHiRes(void)
  710. {
  711. unsigned int lo_c, hi_c;
  712. __asm__ __volatile__ (
  713. "rdtsc"
  714. : "=a"(lo_c), "=d"(hi_c) /* out */
  715. : "a"(0) /* in */
  716. : "%ebx", "%ecx"); /* clobber */
  717. return ((word64)lo_c) | (((word64)hi_c) << 32);
  718. }
  719. #elif !defined(ENTROPY_MEMUSE_THREAD) && \
  720. (defined(__APPLE__) || defined(__MACH__))
  721. /* Get the high resolution time counter.
  722. *
  723. * @return 64-bit time in nanoseconds.
  724. */
  725. static WC_INLINE word64 Entropy_TimeHiRes(void)
  726. {
  727. return mach_absolute_time();
  728. }
  729. #elif !defined(ENTROPY_MEMUSE_THREAD) && defined(__aarch64__)
  730. /* Get the high resolution time counter.
  731. *
  732. * @return 64-bit timer count.
  733. */
  734. static WC_INLINE word64 Entropy_TimeHiRes(void)
  735. {
  736. word64 cnt;
  737. __asm__ __volatile__ (
  738. "mrs %[cnt], cntvct_el0"
  739. : [cnt] "=r"(cnt)
  740. :
  741. :
  742. );
  743. return cnt;
  744. }
  745. #elif !defined(ENTROPY_MEMUSE_THREAD) && (_POSIX_C_SOURCE >= 199309L)
  746. /* Get the high resolution time counter.
  747. *
  748. * @return 64-bit time that is the nanoseconds of current time.
  749. */
  750. static WC_INLINE word64 Entropy_TimeHiRes(void)
  751. {
  752. struct timespec now;
  753. clock_gettime(CLOCK_REALTIME, &now);
  754. return now.tv_nsec;
  755. }
  756. #elif !defined(SINGLE_THREADED) && defined(_POSIX_THREADS) && \
  757. !defined(__MINGW32__)
  758. /* Start and stop thread that counts as a proxy for time counter. */
  759. #define ENTROPY_MEMUSE_THREADED
  760. /* Data for entropy thread. */
  761. typedef struct ENTROPY_THREAD_DATA {
  762. /* Current counter - proxy for time. */
  763. word64 counter;
  764. /* Whether to stop thread. */
  765. int stop;
  766. } ENTROPY_THREAD_DATA;
  767. /* Track whether entropy thread has been started already. */
  768. static int entropy_thread_started = 0;
  769. /* Cache thread id for joining on exit. */
  770. static THREAD_TYPE entropy_thread_id = 0;
  771. /* Data for thread to update/observer. */
  772. static volatile ENTROPY_THREAD_DATA entropy_thread_data = { 0, 0 };
  773. /* Get the high resolution time counter. Counter incremented in thread.
  774. *
  775. * @return 64-bit counter.
  776. */
  777. static WC_INLINE word64 Entropy_TimeHiRes(void)
  778. {
  779. /* Return counter update in thread. */
  780. return entropy_thread_data.counter;
  781. }
  782. /* Thread that increments counter while not told to stop.
  783. *
  784. * @param [in,out] args Entropy data including: counter and stop flag.
  785. * @return NULL always.
  786. */
  787. static THREAD_RETURN WOLFSSL_THREAD Entropy_IncCounter(void* args)
  788. {
  789. (void)args;
  790. /* Thread resources to be disposed of. */
  791. pthread_detach(pthread_self());
  792. /* Keep going until caller tells us to stop and exit. */
  793. while (!entropy_thread_data.stop) {
  794. /* Increment counter acting as high resolution timer. */
  795. entropy_thread_data.counter++;
  796. }
  797. #ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
  798. fprintf(stderr, "EXITING ENTROPY COUNTER THREAD\n");
  799. #endif
  800. /* Exit from thread. */
  801. pthread_exit(NULL);
  802. }
  803. /* Start a thread that increments counter if not one already.
  804. *
  805. * Won't start a new thread if one already running.
  806. * Waits for thread to start by waiting for counter to have incremented.
  807. *
  808. * @return 0 on success.
  809. * @return Negative on failure.
  810. */
  811. static int Entropy_StartThread(void)
  812. {
  813. int ret = 0;
  814. /* Only continue if we haven't started a thread. */
  815. if (!entropy_thread_started) {
  816. /* Get counter before starting thread. */
  817. word64 start_counter = entropy_thread_data.counter;
  818. /* In case of restarting thread, set stop indicator to false. */
  819. entropy_thread_data.stop = 0;
  820. #ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
  821. fprintf(stderr, "STARTING ENTROPY COUNTER THREAD\n");
  822. #endif
  823. /* Create a thread that increments the counter in the data. */
  824. ret = pthread_create(&entropy_thread_id, NULL, Entropy_IncCounter,
  825. NULL);
  826. if (ret == 0) {
  827. /* Wait for the counter to increase indicating thread started. */
  828. while (entropy_thread_data.counter == start_counter) {
  829. sched_yield();
  830. }
  831. }
  832. entropy_thread_started = (ret == 0);
  833. }
  834. return ret;
  835. }
  836. /* Tell thread to stop and wait for it to complete.
  837. *
  838. * Called by wolfCrypt_Cleanup().
  839. */
  840. static void Entropy_StopThread(void)
  841. {
  842. /* Only stop a thread if one is running. */
  843. if (entropy_thread_started) {
  844. /* Tell thread to stop. */
  845. entropy_thread_data.stop = 1;
  846. /* Stopped thread so no thread started anymore. */
  847. entropy_thread_started = 0;
  848. }
  849. }
  850. #else
  851. #error "No high precision time available for MemUse Entropy."
  852. #endif
  853. #ifndef ENTROPY_NUM_WORDS_BITS
  854. /* Number of bits to count of 64-bit words in state. */
  855. #define ENTROPY_NUM_WORDS_BITS 14
  856. #endif
  857. /* Floor of 8 yields pool of 256x 64-bit word samples
  858. * 9 -> 512x 64-bit word samples
  859. * 10 -> 1,024x 64-bit word samples
  860. * 11 -> 2,048x 64-bit word samples
  861. * 12 -> 4,096x 64-bit word samples
  862. * 13 -> 8,192x 64-bit word samples
  863. * 14 -> 16,384x 64-bit word samples
  864. * 15 -> 32,768x 64-bit word samples
  865. * ... doubling every time up to a maximum of:
  866. * 30 -> 1,073,741,824x 64-bit word samples
  867. * 1 billion+ samples should be more then sufficient for any use-case
  868. */
  869. #if ENTROPY_NUM_WORDS_BITS < 8
  870. #error "ENTROPY_NUM_WORDS_BITS must be 8 or more"
  871. #elif ENTROPY_NUM_WORDS_BITS > 30
  872. #error "ENTROPY_NUM_WORDS_BITS must be less than 31"
  873. #endif
  874. /* Number of 64-bit words in state. */
  875. #define ENTROPY_NUM_WORDS (1 << ENTROPY_NUM_WORDS_BITS)
  876. /* Size of one block of 64-bit words. */
  877. #define ENTROPY_BLOCK_SZ (ENTROPY_NUM_WORDS_BITS - 8)
  878. #ifndef ENTROPY_NUM_UPDATES
  879. /* Number of times to update random blocks.
  880. * Less than 2^ENTROPY_BLOCK_SZ (default: 2^6 = 64).
  881. * Maximize value to maximize entropy per sample.
  882. * Limit value to ensure entropy is collected in a timely manner.
  883. */
  884. #define ENTROPY_NUM_UPDATES 18
  885. /* Upper round of log2(ENTROPY_NUM_UPDATES) */
  886. #define ENTROPY_NUM_UPDATES_BITS 5
  887. #elif !defined(ENTROPY_NUM_UPDATES_BITS)
  888. #define ENTROPY_NUM_UPDATES_BITS ENTROPY_BLOCK_SZ
  889. #endif
  890. /* Amount to shift offset to get better coverage of a block */
  891. #define ENTROPY_OFFSET_SHIFTING \
  892. (ENTROPY_BLOCK_SZ / ENTROPY_NUM_UPDATES_BITS)
  893. #ifndef ENTROPY_NUM_64BIT_WORDS
  894. /* Number of 64-bit words to update - 32. */
  895. #define ENTROPY_NUM_64BIT_WORDS WC_SHA3_256_DIGEST_SIZE
  896. #elif ENTROPY_NUM_64BIT_WORDS > WC_SHA3_256_DIGEST_SIZE
  897. #error "ENTROPY_NUM_64BIT_WORDS must be <= SHA3-256 digest size in bytes"
  898. #endif
  899. /* State to update that is multiple cache lines long. */
  900. static word64 entropy_state[ENTROPY_NUM_WORDS] = {0};
  901. /* Using memory will take different amount of times depending on the CPU's
  902. * caches and business.
  903. */
  904. static void Entropy_MemUse(void)
  905. {
  906. int i;
  907. static byte d[WC_SHA3_256_DIGEST_SIZE];
  908. int j;
  909. for (j = 0; j < ENTROPY_NUM_UPDATES; j++) {
  910. /* Hash the first 32 64-bit words of state. */
  911. wc_Sha3_256_Update(&entropyHash, (byte*)entropy_state,
  912. sizeof(*entropy_state) * ENTROPY_NUM_64BIT_WORDS);
  913. /* Get pseudo-random indices. */
  914. wc_Sha3_256_Final(&entropyHash, d);
  915. for (i = 0; i < ENTROPY_NUM_64BIT_WORDS; i++) {
  916. /* Choose a 64-bit word from a pseudo-random block.*/
  917. int idx = ((int)d[i] << ENTROPY_BLOCK_SZ) +
  918. (j << ENTROPY_OFFSET_SHIFTING);
  919. /* Update a pseudo-random 64-bit word with a pseudo-random value. */
  920. entropy_state[idx] += Entropy_TimeHiRes();
  921. /* Ensure part of state that is hashed is updated. */
  922. entropy_state[i] += entropy_state[idx];
  923. }
  924. }
  925. }
  926. /* Last time entropy sample was gathered. */
  927. static word64 entropy_last_time = 0;
  928. /* Get a sample of noise.
  929. *
  930. * Value is time taken to use memory.
  931. *
  932. * Called to test raw entropy.
  933. *
  934. * @return 64-bit value that is the noise.
  935. */
  936. static word64 Entropy_GetSample(void)
  937. {
  938. word64 now;
  939. word64 ret;
  940. /* Use memory such that it will take an unpredictable amount of time. */
  941. Entropy_MemUse();
  942. /* Get the time now to subtract from previous end time. */
  943. now = Entropy_TimeHiRes();
  944. /* Calculate time diff since last sampling. */
  945. ret = now - entropy_last_time;
  946. /* Store last time. */
  947. entropy_last_time = now;
  948. return ret;
  949. }
  950. /* Get as many samples of noise as required.
  951. *
  952. * One sample is one byte.
  953. *
  954. * @param [out] noise Buffer to hold samples.
  955. * @param [in] samples Number of one byte samples to get.
  956. */
  957. static void Entropy_GetNoise(unsigned char* noise, int samples)
  958. {
  959. int i;
  960. /* Do it once to get things going. */
  961. Entropy_MemUse();
  962. /* Get as many samples as required. */
  963. for (i = 0; i < samples; i++) {
  964. noise[i] = (byte)Entropy_GetSample();
  965. }
  966. }
  967. /* Generate raw entropy for performing assessment.
  968. *
  969. * @param [out] raw Buffer to hold raw entropy data.
  970. * @param [in] cnt Number of bytes of raw entropy to get.
  971. * @return 0 on success.
  972. * @return Negative when creating a thread fails - when no high resolution
  973. * clock available.
  974. */
  975. int wc_Entropy_GetRawEntropy(unsigned char* raw, int cnt)
  976. {
  977. int ret = 0;
  978. #ifdef ENTROPY_MEMUSE_THREADED
  979. /* Start the counter thread as a proxy for time counter. */
  980. ret = Entropy_StartThread();
  981. if (ret == 0)
  982. #endif
  983. {
  984. Entropy_GetNoise(raw, cnt);
  985. }
  986. #ifdef ENTROPY_MEMUSE_THREADED
  987. /* Stop the counter thread to avoid thrashing the system. */
  988. Entropy_StopThread();
  989. #endif
  990. return ret;
  991. }
  992. #if ENTROPY_MIN == 1
  993. /* SP800-90b 4.4.1 - Repetition Test
  994. * C = 1 + upper(-log2(alpha) / H)
  995. * When alpha = 2^-30 and H = 1,
  996. * C = 1 + upper(30 / 1) = 31
  997. */
  998. #define REP_CUTOFF 31
  999. #else
  1000. #error "Minimum entropy not defined to a recognized value."
  1001. #endif
  1002. /* Have valid previous sample for repetition test. */
  1003. static int rep_have_prev = 0;
  1004. /* Previous sample value. */
  1005. static byte rep_prev_noise;
  1006. static void Entropy_HealthTest_Repetition_Reset(void)
  1007. {
  1008. /* No previous stored. */
  1009. rep_have_prev = 0;
  1010. /* Clear previous. */
  1011. rep_prev_noise = 0;
  1012. }
  1013. /* Test sample value with repetition test.
  1014. *
  1015. * @param [in] noise Sample to test.
  1016. * @return 0 on success.
  1017. * @return ENTROPY_RT_E on failure.
  1018. */
  1019. static int Entropy_HealthTest_Repetition(byte noise)
  1020. {
  1021. int ret = 0;
  1022. /* Number of times previous value has been seen continuously. */
  1023. static int rep_cnt = 0;
  1024. /* If we don't have a previous then store this one for next time. */
  1025. if (!rep_have_prev) {
  1026. rep_prev_noise = noise;
  1027. rep_have_prev = 1;
  1028. }
  1029. /* Check whether this sample matches last. */
  1030. else if (noise == rep_prev_noise) {
  1031. /* Update count of repetitions. */
  1032. rep_cnt++;
  1033. /* Fail if we reach cutoff. */
  1034. if (rep_cnt >= REP_CUTOFF) {
  1035. #ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
  1036. fprintf(stderr, "REPETITION FAILED: %d\n", noise);
  1037. #endif
  1038. Entropy_HealthTest_Repetition_Reset();
  1039. ret = ENTROPY_RT_E;
  1040. }
  1041. }
  1042. else {
  1043. /* Cache new previous and seen one so far. */
  1044. rep_prev_noise = noise;
  1045. rep_cnt = 1;
  1046. }
  1047. return ret;
  1048. }
  1049. /* SP800-90b 4.4.2 - Adaptive Proportion Test
  1050. * Para 2
  1051. * ... The window size W is selected based on the alphabet size ... 512 if
  1052. * the noise source is not binary ...
  1053. */
  1054. #define PROP_WINDOW_SIZE 512
  1055. #if ENTROPY_MIN == 1
  1056. /* SP800-90b 4.4.2 - Adaptive Proportion Test
  1057. * Note 10
  1058. * C = 1 + CRITBINOM(W, power(2,( -H)),1-alpha)
  1059. * alpa = 2^-30 = POWER(2,-30), H = 1, W = 512
  1060. * C = 1 + CRITBINOM(512, 0.5, 1-POWER(2,-30)) = 1 + 324 = 325
  1061. */
  1062. #define PROP_CUTOFF 325
  1063. #else
  1064. #error "Minimum entropy not defined to a recognized value."
  1065. #endif
  1066. /* Total number of samples storef for Adaptive proportion test.
  1067. * Need the next 512 samples to compare this this one.
  1068. */
  1069. static word16 prop_total = 0;
  1070. /* Index of first sample. */
  1071. static word16 prop_first = 0;
  1072. /* Index to put next sample in. */
  1073. static word16 prop_last = 0;
  1074. /* Count of each value seen in queue. */
  1075. static word16 prop_cnt[1 << ENTROPY_BITS_USED] = { 0 };
  1076. /* Circular queue of samples. */
  1077. static word16 prop_samples[PROP_WINDOW_SIZE];
  1078. /* Resets the data for the Adaptive Proportion Test.
  1079. */
  1080. static void Entropy_HealthTest_Proportion_Reset(void)
  1081. {
  1082. /* Clear out samples. */
  1083. XMEMSET(prop_samples, 0, sizeof(prop_samples));
  1084. /* Clear out counts. */
  1085. XMEMSET(prop_cnt, 0, sizeof(prop_cnt));
  1086. /* Clear stored count. */
  1087. prop_total = 0;
  1088. /* Reset first and last index for samples. */
  1089. prop_first = 0;
  1090. prop_last = 0;
  1091. }
  1092. /* Add sample to Adaptive Proportion test.
  1093. *
  1094. * SP800-90b 4.4.2 - Adaptive Proportion Test
  1095. *
  1096. * Sample is accumulated into buffer until required successive values seen.
  1097. *
  1098. * @param [in] noise Sample to test.
  1099. * @return 0 on success.
  1100. * @return ENTROPY_APT_E on failure.
  1101. */
  1102. static int Entropy_HealthTest_Proportion(byte noise)
  1103. {
  1104. int ret = 0;
  1105. /* Need at least 512-1 samples to test with. */
  1106. if (prop_total < PROP_WINDOW_SIZE - 1) {
  1107. /* Store sample at last position in circular queue. */
  1108. prop_samples[prop_last++] = noise;
  1109. /* Update count of seen value based on new sample. */
  1110. prop_cnt[noise]++;
  1111. /* Update count of store values. */
  1112. prop_total++;
  1113. }
  1114. else {
  1115. /* Get first value in queue - value to test. */
  1116. byte val = prop_samples[prop_first];
  1117. /* Store new sample in queue. */
  1118. prop_samples[prop_last] = noise;
  1119. /* Update first index now that we have removed in from the queue. */
  1120. prop_first = (prop_first + 1) % PROP_WINDOW_SIZE;
  1121. /* Update last index now that we have added new sample to queue. */
  1122. prop_last = (prop_last + 1) % PROP_WINDOW_SIZE;
  1123. /* Removed sample from queue - remove count. */
  1124. prop_cnt[val]--;
  1125. /* Added sample to queue - add count. */
  1126. prop_cnt[noise]++;
  1127. /* Check whether removed value has too many repetitions in queue. */
  1128. if (prop_cnt[val] >= PROP_CUTOFF) {
  1129. #ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
  1130. fprintf(stderr, "PROPORTION FAILED: %d %d\n", val, prop_cnt[val]);
  1131. #endif
  1132. Entropy_HealthTest_Proportion_Reset();
  1133. /* Error code returned. */
  1134. ret = ENTROPY_APT_E;
  1135. }
  1136. }
  1137. return ret;
  1138. }
  1139. /* SP800-90b 4.3 - Requirements for Health Tests
  1140. * 1.4: The entropy source's startup tests shall run the continuous health
  1141. * tests over at least 1024 consecutive samples.
  1142. *
  1143. * Adaptive Proportion Test requires a number of samples to compared too.
  1144. */
  1145. #define ENTROPY_INITIAL_COUNT (1024 + PROP_WINDOW_SIZE)
  1146. /* Perform startup health testing.
  1147. *
  1148. * Fill adaptive proportion test buffer and then do 1024 samples.
  1149. * Perform repetition test on all samples expect last.
  1150. *
  1151. * Discards samples from health tests on failure.
  1152. *
  1153. * @return 0 on success.
  1154. * @return ENTROPY_RT_E or ENTROPY_APT_E on failure.
  1155. */
  1156. static int Entropy_HealthTest_Startup(void)
  1157. {
  1158. int ret = 0;
  1159. byte initial[ENTROPY_INITIAL_COUNT];
  1160. int i;
  1161. #ifdef WOLFSSL_DEBUG_ENTROPY_MEMUSE
  1162. fprintf(stderr, "STARTUP HEALTH TEST\n");
  1163. #endif
  1164. /* Fill initial sample buffer with noise. */
  1165. Entropy_GetNoise(initial, ENTROPY_INITIAL_COUNT);
  1166. /* Health check initial noise. */
  1167. for (i = 0; (ret == 0) && (i < ENTROPY_INITIAL_COUNT); i++) {
  1168. ret = Entropy_HealthTest_Repetition(initial[i]);
  1169. if (ret == 0) {
  1170. ret = Entropy_HealthTest_Proportion(initial[i]);
  1171. }
  1172. }
  1173. if (ret != 0) {
  1174. /* Failing test only resets its own data. */
  1175. Entropy_HealthTest_Reset();
  1176. }
  1177. return ret;
  1178. }
  1179. /* Condition raw entropy noise using SHA-3-256.
  1180. *
  1181. * Put noise into a hash function: SHA-3-256.
  1182. * Add the current time counter to help with uniqueness.
  1183. *
  1184. * @param [out] output Buffer to conditioned data.
  1185. * @param [in] len Number of bytes to put into output buffer.
  1186. * @param [in] noise Buffer with raw noise data.
  1187. * @param [in] noise_len Length of noise data in bytes.
  1188. * @return 0 on success.
  1189. * @return Negative on failure.
  1190. */
  1191. static int Entropy_Condition(byte* output, word32 len, byte* noise,
  1192. word32 noise_len)
  1193. {
  1194. int ret;
  1195. /* Add noise to initialized hash. */
  1196. ret = wc_Sha3_256_Update(&entropyHash, noise, noise_len);
  1197. if (ret == 0) {
  1198. word64 now = Entropy_TimeHiRes();
  1199. /* Add time now counter. */
  1200. ret = wc_Sha3_256_Update(&entropyHash, (byte*)&now, sizeof(now));
  1201. }
  1202. if (ret == 0) {
  1203. /* Finalize into output buffer. */
  1204. if (len == WC_SHA3_256_DIGEST_SIZE) {
  1205. ret = wc_Sha3_256_Final(&entropyHash, output);
  1206. }
  1207. else {
  1208. byte hash[WC_SHA3_256_DIGEST_SIZE];
  1209. ret = wc_Sha3_256_Final(&entropyHash, hash);
  1210. if (ret == 0) {
  1211. XMEMCPY(output, hash, len);
  1212. }
  1213. }
  1214. }
  1215. return ret;
  1216. }
  1217. /* Mutex to prevent multiple callers requesting entropy operations at the
  1218. * same time.
  1219. */
  1220. static wolfSSL_Mutex entropy_mutex;
  1221. /* Get entropy of specified strength.
  1222. *
  1223. * SP800-90b 2.3.1 - GetEntropy: An Interface to the Entropy Source
  1224. *
  1225. * In threaded environment, only one thread at a time can get entropy.
  1226. *
  1227. * @param [in] bits Number of entropy bits. 256 is max value.
  1228. * @param [out] entropy Buffer to hold entropy.
  1229. * @param [in] len Length of data to put into buffer in bytes.
  1230. * @return 0 on success.
  1231. * @return ENTROPY_RT_E or ENTROPY_APT_E on failure.
  1232. * @return BAD_MUTEX_E when unable to lock mutex.
  1233. */
  1234. int wc_Entropy_Get(int bits, unsigned char* entropy, word32 len)
  1235. {
  1236. int ret = 0;
  1237. byte noise[MAX_NOISE_CNT];
  1238. /* Noise length is the number of 8 byte samples required to get the bits of
  1239. * entropy requested. */
  1240. int noise_len = (bits + ENTROPY_EXTRA) / ENTROPY_MIN;
  1241. /* Lock the mutex as collection uses globals. */
  1242. if (wc_LockMutex(&entropy_mutex) != 0) {
  1243. ret = BAD_MUTEX_E;
  1244. }
  1245. #ifdef ENTROPY_MEMUSE_THREADED
  1246. if (ret == 0) {
  1247. /* Start the counter thread as a proxy for time counter. */
  1248. ret = Entropy_StartThread();
  1249. }
  1250. #endif
  1251. /* Check we have had a startup health check pass. */
  1252. if ((ret == 0) && ((prop_total == 0) || (!rep_have_prev))) {
  1253. /* Try again as check failed. */
  1254. ret = Entropy_HealthTest_Startup();
  1255. }
  1256. /* Keep putting data into buffer until full. */
  1257. while ((ret == 0) && (len > 0)) {
  1258. int i;
  1259. word32 entropy_len = WC_SHA3_256_DIGEST_SIZE;
  1260. /* Output 32 bytes at a time unless buffer has fewer bytes remaining. */
  1261. if (len < entropy_len) {
  1262. entropy_len = len;
  1263. }
  1264. /* Get raw entropy noise. */
  1265. Entropy_GetNoise(noise, noise_len);
  1266. /* Health check each noise value. */
  1267. for (i = 0; (ret == 0) && (i < noise_len); i++) {
  1268. ret = Entropy_HealthTest_Repetition(noise[i]);
  1269. if (ret == 0) {
  1270. ret = Entropy_HealthTest_Proportion(noise[i]);
  1271. }
  1272. }
  1273. if (ret == 0) {
  1274. /* Condition noise value down to 32-bytes or less. */
  1275. ret = Entropy_Condition(entropy, entropy_len, noise, noise_len);
  1276. }
  1277. if (ret == 0) {
  1278. /* Update buffer pointer and count of bytes left to generate. */
  1279. entropy += entropy_len;
  1280. len -= entropy_len;
  1281. }
  1282. }
  1283. #ifdef ENTROPY_MEMUSE_THREADED
  1284. /* Stop the counter thread to avoid thrashing the system. */
  1285. Entropy_StopThread();
  1286. #endif
  1287. if (ret != BAD_MUTEX_E) {
  1288. /* Unlock mutex now we are done. */
  1289. wc_UnLockMutex(&entropy_mutex);
  1290. }
  1291. return ret;
  1292. }
  1293. /* Performs on-demand testing.
  1294. *
  1295. * In threaded environment, locks out other threads from getting entropy.
  1296. *
  1297. * @return 0 on success.
  1298. * @return ENTROPY_RT_E or ENTROPY_APT_E on failure.
  1299. * @return BAD_MUTEX_E when unable to lock mutex.
  1300. */
  1301. int wc_Entropy_OnDemandTest()
  1302. {
  1303. int ret = 0;
  1304. /* Lock the mutex as we don't want collecting to happen during testing. */
  1305. if (wc_LockMutex(&entropy_mutex) != 0) {
  1306. ret = BAD_MUTEX_E;
  1307. }
  1308. if (ret == 0) {
  1309. /* Reset health test state for startup test. */
  1310. Entropy_HealthTest_Reset();
  1311. /* Perform startup tests. */
  1312. ret = Entropy_HealthTest_Startup();
  1313. }
  1314. if (ret != BAD_MUTEX_E) {
  1315. /* Unlock mutex now we are done. */
  1316. wc_UnLockMutex(&entropy_mutex);
  1317. }
  1318. return ret;
  1319. }
  1320. /* Initialize global state for MemUse Entropy and do startup health test.
  1321. *
  1322. * @return 0 on success.
  1323. * @return Negative on failure.
  1324. */
  1325. int Entropy_Init()
  1326. {
  1327. int ret = 0;
  1328. /* Check whether initialization has succeeded before. */
  1329. if (!entropy_memuse_initialized) {
  1330. #ifndef SINGLE_THREADED
  1331. ret = wc_InitMutex(&entropy_mutex);
  1332. #endif
  1333. if (ret == 0) {
  1334. /* Initialize a SHA3-256 object for use in entropy operations. */
  1335. ret = wc_InitSha3_256(&entropyHash, NULL, INVALID_DEVID);
  1336. }
  1337. /* Set globals initialized. */
  1338. entropy_memuse_initialized = (ret == 0);
  1339. if (ret == 0) {
  1340. #ifdef ENTROPY_MEMUSE_THREADED
  1341. /* Start the counter thread as a proxy for time counter. */
  1342. ret = Entropy_StartThread();
  1343. if (ret == 0)
  1344. #endif
  1345. {
  1346. /* Do first startup test now. */
  1347. ret = Entropy_HealthTest_Startup();
  1348. }
  1349. #ifdef ENTROPY_MEMUSE_THREADED
  1350. /* Stop the counter thread to avoid thrashing the system. */
  1351. Entropy_StopThread();
  1352. #endif
  1353. }
  1354. }
  1355. return ret;
  1356. }
  1357. /* Finalize the data associated with the MemUse Entropy source.
  1358. */
  1359. void Entropy_Final()
  1360. {
  1361. /* Only finalize when initialized. */
  1362. if (entropy_memuse_initialized) {
  1363. /* Dispose of the SHA3-356 hash object. */
  1364. wc_Sha3_256_Free(&entropyHash);
  1365. #ifndef SINGLE_THREADED
  1366. wc_FreeMutex(&entropy_mutex);
  1367. #endif
  1368. /* Clear health test data. */
  1369. Entropy_HealthTest_Reset();
  1370. /* No longer initialized. */
  1371. entropy_memuse_initialized = 0;
  1372. }
  1373. }
  1374. /* Reset the data associated with the MemUse Entropy health tests.
  1375. */
  1376. static void Entropy_HealthTest_Reset(void)
  1377. {
  1378. Entropy_HealthTest_Repetition_Reset();
  1379. Entropy_HealthTest_Proportion_Reset();
  1380. }
  1381. #endif /* HAVE_ENTROPY_MEMUSE */
  1382. static int _InitRng(WC_RNG* rng, byte* nonce, word32 nonceSz,
  1383. void* heap, int devId)
  1384. {
  1385. int ret = 0;
  1386. #ifdef HAVE_HASHDRBG
  1387. word32 seedSz = SEED_SZ + SEED_BLOCK_SZ;
  1388. #endif
  1389. (void)nonce;
  1390. (void)nonceSz;
  1391. if (rng == NULL)
  1392. return BAD_FUNC_ARG;
  1393. if (nonce == NULL && nonceSz != 0)
  1394. return BAD_FUNC_ARG;
  1395. #ifdef WOLFSSL_HEAP_TEST
  1396. rng->heap = (void*)WOLFSSL_HEAP_TEST;
  1397. (void)heap;
  1398. #else
  1399. rng->heap = heap;
  1400. #endif
  1401. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
  1402. rng->devId = devId;
  1403. #if defined(WOLF_CRYPTO_CB)
  1404. rng->seed.devId = devId;
  1405. #endif
  1406. #else
  1407. (void)devId;
  1408. #endif
  1409. #ifdef HAVE_HASHDRBG
  1410. /* init the DBRG to known values */
  1411. rng->drbg = NULL;
  1412. rng->status = DRBG_NOT_INIT;
  1413. #endif
  1414. #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND) || \
  1415. defined(HAVE_AMD_RDSEED)
  1416. /* init the intel RD seed and/or rand */
  1417. wc_InitRng_IntelRD();
  1418. #endif
  1419. /* configure async RNG source if available */
  1420. #ifdef WOLFSSL_ASYNC_CRYPT
  1421. ret = wolfAsync_DevCtxInit(&rng->asyncDev, WOLFSSL_ASYNC_MARKER_RNG,
  1422. rng->heap, rng->devId);
  1423. if (ret != 0) {
  1424. #ifdef HAVE_HASHDRBG
  1425. rng->status = DRBG_OK;
  1426. #endif
  1427. return ret;
  1428. }
  1429. #endif
  1430. #ifdef HAVE_INTEL_RDRAND
  1431. /* if CPU supports RDRAND, use it directly and by-pass DRBG init */
  1432. if (IS_INTEL_RDRAND(intel_flags)) {
  1433. #ifdef HAVE_HASHDRBG
  1434. rng->status = DRBG_OK;
  1435. #endif
  1436. return 0;
  1437. }
  1438. #endif
  1439. #ifdef WOLFSSL_XILINX_CRYPT_VERSAL
  1440. ret = wc_VersalTrngInit(nonce, nonceSz);
  1441. if (ret) {
  1442. #ifdef HAVE_HASHDRBG
  1443. rng->status = DRBG_OK;
  1444. #endif
  1445. return ret;
  1446. }
  1447. #endif
  1448. #ifdef CUSTOM_RAND_GENERATE_BLOCK
  1449. ret = 0; /* success */
  1450. #else
  1451. #ifdef HAVE_HASHDRBG
  1452. if (nonceSz == 0)
  1453. seedSz = MAX_SEED_SZ;
  1454. if (wc_RNG_HealthTestLocal(0) == 0) {
  1455. #ifndef WOLFSSL_SMALL_STACK
  1456. byte seed[MAX_SEED_SZ];
  1457. #else
  1458. byte* seed = (byte*)XMALLOC(MAX_SEED_SZ, rng->heap,
  1459. DYNAMIC_TYPE_SEED);
  1460. if (seed == NULL)
  1461. return MEMORY_E;
  1462. #endif
  1463. #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
  1464. rng->drbg =
  1465. (struct DRBG*)XMALLOC(sizeof(DRBG_internal), rng->heap,
  1466. DYNAMIC_TYPE_RNG);
  1467. if (rng->drbg == NULL) {
  1468. ret = MEMORY_E;
  1469. rng->status = DRBG_FAILED;
  1470. }
  1471. #else
  1472. rng->drbg = (struct DRBG*)&rng->drbg_data;
  1473. #endif
  1474. if (ret == 0) {
  1475. #ifdef WC_RNG_SEED_CB
  1476. if (seedCb == NULL) {
  1477. ret = DRBG_NO_SEED_CB;
  1478. }
  1479. else {
  1480. ret = seedCb(&rng->seed, seed, seedSz);
  1481. if (ret != 0) {
  1482. ret = DRBG_FAILURE;
  1483. }
  1484. }
  1485. #else
  1486. ret = wc_GenerateSeed(&rng->seed, seed, seedSz);
  1487. #endif
  1488. if (ret == 0)
  1489. ret = wc_RNG_TestSeed(seed, seedSz);
  1490. else {
  1491. ret = DRBG_FAILURE;
  1492. rng->status = DRBG_FAILED;
  1493. }
  1494. if (ret == DRBG_SUCCESS)
  1495. ret = Hash_DRBG_Instantiate((DRBG_internal *)rng->drbg,
  1496. seed + SEED_BLOCK_SZ, seedSz - SEED_BLOCK_SZ,
  1497. nonce, nonceSz, rng->heap, devId);
  1498. if (ret != DRBG_SUCCESS) {
  1499. #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
  1500. XFREE(rng->drbg, rng->heap, DYNAMIC_TYPE_RNG);
  1501. #endif
  1502. rng->drbg = NULL;
  1503. }
  1504. }
  1505. ForceZero(seed, seedSz);
  1506. #ifdef WOLFSSL_SMALL_STACK
  1507. XFREE(seed, rng->heap, DYNAMIC_TYPE_SEED);
  1508. #endif
  1509. }
  1510. else {
  1511. ret = DRBG_CONT_FAILURE;
  1512. }
  1513. if (ret == DRBG_SUCCESS) {
  1514. #ifdef WOLFSSL_CHECK_MEM_ZERO
  1515. #ifdef HAVE_HASHDRBG
  1516. struct DRBG_internal* drbg = (struct DRBG_internal*)rng->drbg;
  1517. wc_MemZero_Add("DRBG V", &drbg->V, sizeof(drbg->V));
  1518. wc_MemZero_Add("DRBG C", &drbg->C, sizeof(drbg->C));
  1519. #endif
  1520. #endif
  1521. rng->status = DRBG_OK;
  1522. ret = 0;
  1523. }
  1524. else if (ret == DRBG_CONT_FAILURE) {
  1525. rng->status = DRBG_CONT_FAILED;
  1526. ret = DRBG_CONT_FIPS_E;
  1527. }
  1528. else if (ret == DRBG_FAILURE) {
  1529. rng->status = DRBG_FAILED;
  1530. ret = RNG_FAILURE_E;
  1531. }
  1532. else {
  1533. rng->status = DRBG_FAILED;
  1534. }
  1535. #endif /* HAVE_HASHDRBG */
  1536. #endif /* CUSTOM_RAND_GENERATE_BLOCK */
  1537. return ret;
  1538. }
  1539. WOLFSSL_ABI
  1540. WC_RNG* wc_rng_new(byte* nonce, word32 nonceSz, void* heap)
  1541. {
  1542. WC_RNG* rng;
  1543. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), heap, DYNAMIC_TYPE_RNG);
  1544. if (rng) {
  1545. int error = _InitRng(rng, nonce, nonceSz, heap, INVALID_DEVID) != 0;
  1546. if (error) {
  1547. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  1548. rng = NULL;
  1549. }
  1550. }
  1551. return rng;
  1552. }
  1553. WOLFSSL_ABI
  1554. void wc_rng_free(WC_RNG* rng)
  1555. {
  1556. if (rng) {
  1557. void* heap = rng->heap;
  1558. wc_FreeRng(rng);
  1559. ForceZero(rng, sizeof(WC_RNG));
  1560. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  1561. (void)heap;
  1562. }
  1563. }
  1564. WOLFSSL_ABI
  1565. int wc_InitRng(WC_RNG* rng)
  1566. {
  1567. return _InitRng(rng, NULL, 0, NULL, INVALID_DEVID);
  1568. }
  1569. int wc_InitRng_ex(WC_RNG* rng, void* heap, int devId)
  1570. {
  1571. return _InitRng(rng, NULL, 0, heap, devId);
  1572. }
  1573. int wc_InitRngNonce(WC_RNG* rng, byte* nonce, word32 nonceSz)
  1574. {
  1575. return _InitRng(rng, nonce, nonceSz, NULL, INVALID_DEVID);
  1576. }
  1577. int wc_InitRngNonce_ex(WC_RNG* rng, byte* nonce, word32 nonceSz,
  1578. void* heap, int devId)
  1579. {
  1580. return _InitRng(rng, nonce, nonceSz, heap, devId);
  1581. }
  1582. /* place a generated block in output */
  1583. WOLFSSL_ABI
  1584. int wc_RNG_GenerateBlock(WC_RNG* rng, byte* output, word32 sz)
  1585. {
  1586. int ret;
  1587. if (rng == NULL || output == NULL)
  1588. return BAD_FUNC_ARG;
  1589. if (sz == 0)
  1590. return 0;
  1591. #ifdef WOLF_CRYPTO_CB
  1592. #ifndef WOLF_CRYPTO_CB_FIND
  1593. if (rng->devId != INVALID_DEVID)
  1594. #endif
  1595. {
  1596. ret = wc_CryptoCb_RandomBlock(rng, output, sz);
  1597. if (ret != CRYPTOCB_UNAVAILABLE)
  1598. return ret;
  1599. /* fall-through when unavailable */
  1600. }
  1601. #endif
  1602. #ifdef HAVE_INTEL_RDRAND
  1603. if (IS_INTEL_RDRAND(intel_flags))
  1604. return wc_GenerateRand_IntelRD(NULL, output, sz);
  1605. #endif
  1606. #if defined(WOLFSSL_SILABS_SE_ACCEL) && defined(WOLFSSL_SILABS_TRNG)
  1607. return silabs_GenerateRand(output, sz);
  1608. #endif
  1609. #if defined(WOLFSSL_ASYNC_CRYPT)
  1610. if (rng->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RNG) {
  1611. /* these are blocking */
  1612. #ifdef HAVE_CAVIUM
  1613. return NitroxRngGenerateBlock(rng, output, sz);
  1614. #elif defined(HAVE_INTEL_QA) && defined(QAT_ENABLE_RNG)
  1615. return IntelQaDrbg(&rng->asyncDev, output, sz);
  1616. #else
  1617. /* simulator not supported */
  1618. #endif
  1619. }
  1620. #endif
  1621. #ifdef CUSTOM_RAND_GENERATE_BLOCK
  1622. XMEMSET(output, 0, sz);
  1623. ret = (int)CUSTOM_RAND_GENERATE_BLOCK(output, sz);
  1624. #else
  1625. #ifdef HAVE_HASHDRBG
  1626. if (sz > RNG_MAX_BLOCK_LEN)
  1627. return BAD_FUNC_ARG;
  1628. if (rng->status != DRBG_OK)
  1629. return RNG_FAILURE_E;
  1630. ret = Hash_DRBG_Generate((DRBG_internal *)rng->drbg, output, sz);
  1631. if (ret == DRBG_NEED_RESEED) {
  1632. if (wc_RNG_HealthTestLocal(1) == 0) {
  1633. #ifndef WOLFSSL_SMALL_STACK
  1634. byte newSeed[SEED_SZ + SEED_BLOCK_SZ];
  1635. ret = DRBG_SUCCESS;
  1636. #else
  1637. byte* newSeed = (byte*)XMALLOC(SEED_SZ + SEED_BLOCK_SZ, rng->heap,
  1638. DYNAMIC_TYPE_SEED);
  1639. ret = (newSeed == NULL) ? MEMORY_E : DRBG_SUCCESS;
  1640. #endif
  1641. if (ret == DRBG_SUCCESS) {
  1642. #ifdef WC_RNG_SEED_CB
  1643. if (seedCb == NULL) {
  1644. ret = DRBG_NO_SEED_CB;
  1645. }
  1646. else {
  1647. ret = seedCb(&rng->seed, newSeed, SEED_SZ + SEED_BLOCK_SZ);
  1648. if (ret != 0) {
  1649. ret = DRBG_FAILURE;
  1650. }
  1651. }
  1652. #else
  1653. ret = wc_GenerateSeed(&rng->seed, newSeed,
  1654. SEED_SZ + SEED_BLOCK_SZ);
  1655. #endif
  1656. if (ret != 0)
  1657. ret = DRBG_FAILURE;
  1658. }
  1659. if (ret == DRBG_SUCCESS)
  1660. ret = wc_RNG_TestSeed(newSeed, SEED_SZ + SEED_BLOCK_SZ);
  1661. if (ret == DRBG_SUCCESS)
  1662. ret = Hash_DRBG_Reseed((DRBG_internal *)rng->drbg,
  1663. newSeed + SEED_BLOCK_SZ, SEED_SZ);
  1664. if (ret == DRBG_SUCCESS)
  1665. ret = Hash_DRBG_Generate((DRBG_internal *)rng->drbg, output, sz);
  1666. ForceZero(newSeed, sizeof(newSeed));
  1667. #ifdef WOLFSSL_SMALL_STACK
  1668. XFREE(newSeed, rng->heap, DYNAMIC_TYPE_SEED);
  1669. #endif
  1670. }
  1671. else {
  1672. ret = DRBG_CONT_FAILURE;
  1673. }
  1674. }
  1675. if (ret == DRBG_SUCCESS) {
  1676. ret = 0;
  1677. }
  1678. else if (ret == DRBG_CONT_FAILURE) {
  1679. ret = DRBG_CONT_FIPS_E;
  1680. rng->status = DRBG_CONT_FAILED;
  1681. }
  1682. else {
  1683. ret = RNG_FAILURE_E;
  1684. rng->status = DRBG_FAILED;
  1685. }
  1686. #else
  1687. /* if we get here then there is an RNG configuration error */
  1688. ret = RNG_FAILURE_E;
  1689. #endif /* HAVE_HASHDRBG */
  1690. #endif /* CUSTOM_RAND_GENERATE_BLOCK */
  1691. return ret;
  1692. }
  1693. int wc_RNG_GenerateByte(WC_RNG* rng, byte* b)
  1694. {
  1695. return wc_RNG_GenerateBlock(rng, b, 1);
  1696. }
  1697. int wc_FreeRng(WC_RNG* rng)
  1698. {
  1699. int ret = 0;
  1700. if (rng == NULL)
  1701. return BAD_FUNC_ARG;
  1702. #if defined(WOLFSSL_ASYNC_CRYPT)
  1703. wolfAsync_DevCtxFree(&rng->asyncDev, WOLFSSL_ASYNC_MARKER_RNG);
  1704. #endif
  1705. #ifdef HAVE_HASHDRBG
  1706. if (rng->drbg != NULL) {
  1707. if (Hash_DRBG_Uninstantiate((DRBG_internal *)rng->drbg) != DRBG_SUCCESS)
  1708. ret = RNG_FAILURE_E;
  1709. #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
  1710. XFREE(rng->drbg, rng->heap, DYNAMIC_TYPE_RNG);
  1711. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  1712. wc_MemZero_Check(rng->drbg, sizeof(DRBG_internal));
  1713. #endif
  1714. rng->drbg = NULL;
  1715. }
  1716. rng->status = DRBG_NOT_INIT;
  1717. #endif /* HAVE_HASHDRBG */
  1718. #ifdef WOLFSSL_XILINX_CRYPT_VERSAL
  1719. /* don't overwrite previously set error */
  1720. if (wc_VersalTrngReset() && !ret)
  1721. ret = WC_HW_E;
  1722. #endif
  1723. return ret;
  1724. }
  1725. #ifdef HAVE_HASHDRBG
  1726. int wc_RNG_HealthTest(int reseed, const byte* seedA, word32 seedASz,
  1727. const byte* seedB, word32 seedBSz,
  1728. byte* output, word32 outputSz)
  1729. {
  1730. return wc_RNG_HealthTest_ex(reseed, NULL, 0,
  1731. seedA, seedASz, seedB, seedBSz,
  1732. output, outputSz,
  1733. NULL, INVALID_DEVID);
  1734. }
  1735. int wc_RNG_HealthTest_ex(int reseed, const byte* nonce, word32 nonceSz,
  1736. const byte* seedA, word32 seedASz,
  1737. const byte* seedB, word32 seedBSz,
  1738. byte* output, word32 outputSz,
  1739. void* heap, int devId)
  1740. {
  1741. int ret = -1;
  1742. DRBG_internal* drbg;
  1743. #ifndef WOLFSSL_SMALL_STACK
  1744. DRBG_internal drbg_var;
  1745. #endif
  1746. if (seedA == NULL || output == NULL) {
  1747. return BAD_FUNC_ARG;
  1748. }
  1749. if (reseed != 0 && seedB == NULL) {
  1750. return BAD_FUNC_ARG;
  1751. }
  1752. if (outputSz != RNG_HEALTH_TEST_CHECK_SIZE) {
  1753. return ret;
  1754. }
  1755. #ifdef WOLFSSL_SMALL_STACK
  1756. drbg = (DRBG_internal*)XMALLOC(sizeof(DRBG_internal), heap,
  1757. DYNAMIC_TYPE_RNG);
  1758. if (drbg == NULL) {
  1759. return MEMORY_E;
  1760. }
  1761. #else
  1762. drbg = &drbg_var;
  1763. #endif
  1764. if (Hash_DRBG_Instantiate(drbg, seedA, seedASz, nonce, nonceSz,
  1765. heap, devId) != 0) {
  1766. goto exit_rng_ht;
  1767. }
  1768. if (reseed) {
  1769. if (Hash_DRBG_Reseed(drbg, seedB, seedBSz) != 0) {
  1770. goto exit_rng_ht;
  1771. }
  1772. }
  1773. /* This call to generate is prescribed by the NIST DRBGVS
  1774. * procedure. The results are thrown away. The known
  1775. * answer test checks the second block of DRBG out of
  1776. * the generator to ensure the internal state is updated
  1777. * as expected. */
  1778. if (Hash_DRBG_Generate(drbg, output, outputSz) != 0) {
  1779. goto exit_rng_ht;
  1780. }
  1781. if (Hash_DRBG_Generate(drbg, output, outputSz) != 0) {
  1782. goto exit_rng_ht;
  1783. }
  1784. /* Mark success */
  1785. ret = 0;
  1786. exit_rng_ht:
  1787. /* This is safe to call even if Hash_DRBG_Instantiate fails */
  1788. if (Hash_DRBG_Uninstantiate(drbg) != 0) {
  1789. ret = -1;
  1790. }
  1791. #ifdef WOLFSSL_SMALL_STACK
  1792. XFREE(drbg, heap, DYNAMIC_TYPE_RNG);
  1793. #endif
  1794. return ret;
  1795. }
  1796. const FLASH_QUALIFIER byte seedA_data[] = {
  1797. 0x63, 0x36, 0x33, 0x77, 0xe4, 0x1e, 0x86, 0x46, 0x8d, 0xeb, 0x0a, 0xb4,
  1798. 0xa8, 0xed, 0x68, 0x3f, 0x6a, 0x13, 0x4e, 0x47, 0xe0, 0x14, 0xc7, 0x00,
  1799. 0x45, 0x4e, 0x81, 0xe9, 0x53, 0x58, 0xa5, 0x69, 0x80, 0x8a, 0xa3, 0x8f,
  1800. 0x2a, 0x72, 0xa6, 0x23, 0x59, 0x91, 0x5a, 0x9f, 0x8a, 0x04, 0xca, 0x68
  1801. };
  1802. const FLASH_QUALIFIER byte reseedSeedA_data[] = {
  1803. 0xe6, 0x2b, 0x8a, 0x8e, 0xe8, 0xf1, 0x41, 0xb6, 0x98, 0x05, 0x66, 0xe3,
  1804. 0xbf, 0xe3, 0xc0, 0x49, 0x03, 0xda, 0xd4, 0xac, 0x2c, 0xdf, 0x9f, 0x22,
  1805. 0x80, 0x01, 0x0a, 0x67, 0x39, 0xbc, 0x83, 0xd3
  1806. };
  1807. const FLASH_QUALIFIER byte outputA_data[] = {
  1808. 0x04, 0xee, 0xc6, 0x3b, 0xb2, 0x31, 0xdf, 0x2c, 0x63, 0x0a, 0x1a, 0xfb,
  1809. 0xe7, 0x24, 0x94, 0x9d, 0x00, 0x5a, 0x58, 0x78, 0x51, 0xe1, 0xaa, 0x79,
  1810. 0x5e, 0x47, 0x73, 0x47, 0xc8, 0xb0, 0x56, 0x62, 0x1c, 0x18, 0xbd, 0xdc,
  1811. 0xdd, 0x8d, 0x99, 0xfc, 0x5f, 0xc2, 0xb9, 0x20, 0x53, 0xd8, 0xcf, 0xac,
  1812. 0xfb, 0x0b, 0xb8, 0x83, 0x12, 0x05, 0xfa, 0xd1, 0xdd, 0xd6, 0xc0, 0x71,
  1813. 0x31, 0x8a, 0x60, 0x18, 0xf0, 0x3b, 0x73, 0xf5, 0xed, 0xe4, 0xd4, 0xd0,
  1814. 0x71, 0xf9, 0xde, 0x03, 0xfd, 0x7a, 0xea, 0x10, 0x5d, 0x92, 0x99, 0xb8,
  1815. 0xaf, 0x99, 0xaa, 0x07, 0x5b, 0xdb, 0x4d, 0xb9, 0xaa, 0x28, 0xc1, 0x8d,
  1816. 0x17, 0x4b, 0x56, 0xee, 0x2a, 0x01, 0x4d, 0x09, 0x88, 0x96, 0xff, 0x22,
  1817. 0x82, 0xc9, 0x55, 0xa8, 0x19, 0x69, 0xe0, 0x69, 0xfa, 0x8c, 0xe0, 0x07,
  1818. 0xa1, 0x80, 0x18, 0x3a, 0x07, 0xdf, 0xae, 0x17
  1819. };
  1820. const FLASH_QUALIFIER byte seedB_data[] = {
  1821. 0xa6, 0x5a, 0xd0, 0xf3, 0x45, 0xdb, 0x4e, 0x0e, 0xff, 0xe8, 0x75, 0xc3,
  1822. 0xa2, 0xe7, 0x1f, 0x42, 0xc7, 0x12, 0x9d, 0x62, 0x0f, 0xf5, 0xc1, 0x19,
  1823. 0xa9, 0xef, 0x55, 0xf0, 0x51, 0x85, 0xe0, 0xfb, /* nonce next */
  1824. 0x85, 0x81, 0xf9, 0x31, 0x75, 0x17, 0x27, 0x6e, 0x06, 0xe9, 0x60, 0x7d,
  1825. 0xdb, 0xcb, 0xcc, 0x2e
  1826. };
  1827. const FLASH_QUALIFIER byte outputB_data[] = {
  1828. 0xd3, 0xe1, 0x60, 0xc3, 0x5b, 0x99, 0xf3, 0x40, 0xb2, 0x62, 0x82, 0x64,
  1829. 0xd1, 0x75, 0x10, 0x60, 0xe0, 0x04, 0x5d, 0xa3, 0x83, 0xff, 0x57, 0xa5,
  1830. 0x7d, 0x73, 0xa6, 0x73, 0xd2, 0xb8, 0xd8, 0x0d, 0xaa, 0xf6, 0xa6, 0xc3,
  1831. 0x5a, 0x91, 0xbb, 0x45, 0x79, 0xd7, 0x3f, 0xd0, 0xc8, 0xfe, 0xd1, 0x11,
  1832. 0xb0, 0x39, 0x13, 0x06, 0x82, 0x8a, 0xdf, 0xed, 0x52, 0x8f, 0x01, 0x81,
  1833. 0x21, 0xb3, 0xfe, 0xbd, 0xc3, 0x43, 0xe7, 0x97, 0xb8, 0x7d, 0xbb, 0x63,
  1834. 0xdb, 0x13, 0x33, 0xde, 0xd9, 0xd1, 0xec, 0xe1, 0x77, 0xcf, 0xa6, 0xb7,
  1835. 0x1f, 0xe8, 0xab, 0x1d, 0xa4, 0x66, 0x24, 0xed, 0x64, 0x15, 0xe5, 0x1c,
  1836. 0xcd, 0xe2, 0xc7, 0xca, 0x86, 0xe2, 0x83, 0x99, 0x0e, 0xea, 0xeb, 0x91,
  1837. 0x12, 0x04, 0x15, 0x52, 0x8b, 0x22, 0x95, 0x91, 0x02, 0x81, 0xb0, 0x2d,
  1838. 0xd4, 0x31, 0xf4, 0xc9, 0xf7, 0x04, 0x27, 0xdf
  1839. };
  1840. static int wc_RNG_HealthTestLocal(int reseed)
  1841. {
  1842. int ret = 0;
  1843. #ifdef WOLFSSL_SMALL_STACK
  1844. byte* check;
  1845. #else
  1846. byte check[RNG_HEALTH_TEST_CHECK_SIZE];
  1847. #endif
  1848. #ifdef WOLFSSL_SMALL_STACK
  1849. check = (byte*)XMALLOC(RNG_HEALTH_TEST_CHECK_SIZE, NULL,
  1850. DYNAMIC_TYPE_TMP_BUFFER);
  1851. if (check == NULL) {
  1852. return MEMORY_E;
  1853. }
  1854. #endif
  1855. if (reseed) {
  1856. #ifdef WOLFSSL_USE_FLASHMEM
  1857. byte* seedA = (byte*)XMALLOC(sizeof(seedA_data), NULL,
  1858. DYNAMIC_TYPE_TMP_BUFFER);
  1859. byte* reseedSeedA = (byte*)XMALLOC(sizeof(reseedSeedA_data), NULL,
  1860. DYNAMIC_TYPE_TMP_BUFFER);
  1861. byte* outputA = (byte*)XMALLOC(sizeof(outputA_data), NULL,
  1862. DYNAMIC_TYPE_TMP_BUFFER);
  1863. if (!seedA || !reseedSeedA || !outputA) {
  1864. XFREE(seedA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1865. XFREE(reseedSeedA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1866. XFREE(outputA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1867. ret = MEMORY_E;
  1868. }
  1869. else {
  1870. XMEMCPY_P(seedA, seedA_data, sizeof(seedA_data));
  1871. XMEMCPY_P(reseedSeedA, reseedSeedA_data, sizeof(reseedSeedA_data));
  1872. XMEMCPY_P(outputA, outputA_data, sizeof(outputA_data));
  1873. #else
  1874. const byte* seedA = seedA_data;
  1875. const byte* reseedSeedA = reseedSeedA_data;
  1876. const byte* outputA = outputA_data;
  1877. #endif
  1878. ret = wc_RNG_HealthTest(1, seedA, sizeof(seedA_data),
  1879. reseedSeedA, sizeof(reseedSeedA_data),
  1880. check, RNG_HEALTH_TEST_CHECK_SIZE);
  1881. if (ret == 0) {
  1882. if (ConstantCompare(check, outputA,
  1883. RNG_HEALTH_TEST_CHECK_SIZE) != 0)
  1884. ret = -1;
  1885. }
  1886. #ifdef WOLFSSL_USE_FLASHMEM
  1887. XFREE(seedA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1888. XFREE(reseedSeedA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1889. XFREE(outputA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1890. }
  1891. #endif
  1892. }
  1893. else {
  1894. #ifdef WOLFSSL_USE_FLASHMEM
  1895. byte* seedB = (byte*)XMALLOC(sizeof(seedB_data), NULL,
  1896. DYNAMIC_TYPE_TMP_BUFFER);
  1897. byte* outputB = (byte*)XMALLOC(sizeof(outputB_data), NULL,
  1898. DYNAMIC_TYPE_TMP_BUFFER);
  1899. if (!seedB || !outputB) {
  1900. XFREE(seedB, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1901. XFREE(outputB, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1902. ret = MEMORY_E;
  1903. }
  1904. else {
  1905. XMEMCPY_P(seedB, seedB_data, sizeof(seedB_data));
  1906. XMEMCPY_P(outputB, outputB_data, sizeof(outputB_data));
  1907. #else
  1908. const byte* seedB = seedB_data;
  1909. const byte* outputB = outputB_data;
  1910. #endif
  1911. ret = wc_RNG_HealthTest(0, seedB, sizeof(seedB_data),
  1912. NULL, 0,
  1913. check, RNG_HEALTH_TEST_CHECK_SIZE);
  1914. if (ret == 0) {
  1915. if (ConstantCompare(check, outputB,
  1916. RNG_HEALTH_TEST_CHECK_SIZE) != 0)
  1917. ret = -1;
  1918. }
  1919. /* The previous test cases use a large seed instead of a seed and nonce.
  1920. * seedB is actually from a test case with a seed and nonce, and
  1921. * just concatenates them. The pivot point between seed and nonce is
  1922. * byte 32, feed them into the health test separately. */
  1923. if (ret == 0) {
  1924. ret = wc_RNG_HealthTest_ex(0,
  1925. seedB + 32, sizeof(seedB_data) - 32,
  1926. seedB, 32,
  1927. NULL, 0,
  1928. check, RNG_HEALTH_TEST_CHECK_SIZE,
  1929. NULL, INVALID_DEVID);
  1930. if (ret == 0) {
  1931. if (ConstantCompare(check, outputB, sizeof(outputB_data)) != 0)
  1932. ret = -1;
  1933. }
  1934. }
  1935. #ifdef WOLFSSL_USE_FLASHMEM
  1936. XFREE(seedB, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1937. XFREE(outputB, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1938. }
  1939. #endif
  1940. }
  1941. #ifdef WOLFSSL_SMALL_STACK
  1942. XFREE(check, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1943. #endif
  1944. return ret;
  1945. }
  1946. #endif /* HAVE_HASHDRBG */
  1947. #ifdef HAVE_WNR
  1948. /*
  1949. * Init global Whitewood netRandom context
  1950. * Returns 0 on success, negative on error
  1951. */
  1952. int wc_InitNetRandom(const char* configFile, wnr_hmac_key hmac_cb, int timeout)
  1953. {
  1954. if (configFile == NULL || timeout < 0)
  1955. return BAD_FUNC_ARG;
  1956. if (wnr_mutex_init > 0) {
  1957. WOLFSSL_MSG("netRandom context already created, skipping");
  1958. return 0;
  1959. }
  1960. if (wc_InitMutex(&wnr_mutex) != 0) {
  1961. WOLFSSL_MSG("Bad Init Mutex wnr_mutex");
  1962. return BAD_MUTEX_E;
  1963. }
  1964. wnr_mutex_init = 1;
  1965. if (wc_LockMutex(&wnr_mutex) != 0) {
  1966. WOLFSSL_MSG("Bad Lock Mutex wnr_mutex");
  1967. return BAD_MUTEX_E;
  1968. }
  1969. /* store entropy timeout */
  1970. wnr_timeout = timeout;
  1971. /* create global wnr_context struct */
  1972. if (wnr_create(&wnr_ctx) != WNR_ERROR_NONE) {
  1973. WOLFSSL_MSG("Error creating global netRandom context");
  1974. return RNG_FAILURE_E;
  1975. }
  1976. /* load config file */
  1977. if (wnr_config_loadf(wnr_ctx, (char*)configFile) != WNR_ERROR_NONE) {
  1978. WOLFSSL_MSG("Error loading config file into netRandom context");
  1979. wnr_destroy(wnr_ctx);
  1980. wnr_ctx = NULL;
  1981. return RNG_FAILURE_E;
  1982. }
  1983. /* create/init polling mechanism */
  1984. if (wnr_poll_create() != WNR_ERROR_NONE) {
  1985. WOLFSSL_MSG("Error initializing netRandom polling mechanism");
  1986. wnr_destroy(wnr_ctx);
  1987. wnr_ctx = NULL;
  1988. return RNG_FAILURE_E;
  1989. }
  1990. /* validate config, set HMAC callback (optional) */
  1991. if (wnr_setup(wnr_ctx, hmac_cb) != WNR_ERROR_NONE) {
  1992. WOLFSSL_MSG("Error setting up netRandom context");
  1993. wnr_destroy(wnr_ctx);
  1994. wnr_ctx = NULL;
  1995. wnr_poll_destroy();
  1996. return RNG_FAILURE_E;
  1997. }
  1998. wc_UnLockMutex(&wnr_mutex);
  1999. return 0;
  2000. }
  2001. /*
  2002. * Free global Whitewood netRandom context
  2003. * Returns 0 on success, negative on error
  2004. */
  2005. int wc_FreeNetRandom(void)
  2006. {
  2007. if (wnr_mutex_init > 0) {
  2008. if (wc_LockMutex(&wnr_mutex) != 0) {
  2009. WOLFSSL_MSG("Bad Lock Mutex wnr_mutex");
  2010. return BAD_MUTEX_E;
  2011. }
  2012. if (wnr_ctx != NULL) {
  2013. wnr_destroy(wnr_ctx);
  2014. wnr_ctx = NULL;
  2015. }
  2016. wnr_poll_destroy();
  2017. wc_UnLockMutex(&wnr_mutex);
  2018. wc_FreeMutex(&wnr_mutex);
  2019. wnr_mutex_init = 0;
  2020. }
  2021. return 0;
  2022. }
  2023. #endif /* HAVE_WNR */
  2024. #if defined(HAVE_INTEL_RDRAND) || defined(HAVE_INTEL_RDSEED) || \
  2025. defined(HAVE_AMD_RDSEED)
  2026. #ifdef WOLFSSL_ASYNC_CRYPT
  2027. /* need more retries if multiple cores */
  2028. #define INTELRD_RETRY (32 * 8)
  2029. #else
  2030. #define INTELRD_RETRY 32
  2031. #endif
  2032. #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED)
  2033. #ifndef USE_INTEL_INTRINSICS
  2034. /* return 0 on success */
  2035. static WC_INLINE int IntelRDseed64(word64* seed)
  2036. {
  2037. unsigned char ok;
  2038. __asm__ volatile("rdseed %0; setc %1":"=r"(*seed), "=qm"(ok));
  2039. return (ok) ? 0 : -1;
  2040. }
  2041. #else /* USE_INTEL_INTRINSICS */
  2042. /* The compiler Visual Studio uses does not allow inline assembly.
  2043. * It does allow for Intel intrinsic functions. */
  2044. /* return 0 on success */
  2045. # ifdef __GNUC__
  2046. __attribute__((target("rdseed")))
  2047. # endif
  2048. static WC_INLINE int IntelRDseed64(word64* seed)
  2049. {
  2050. int ok;
  2051. ok = _rdseed64_step((unsigned long long*) seed);
  2052. return (ok) ? 0 : -1;
  2053. }
  2054. #endif /* USE_INTEL_INTRINSICS */
  2055. /* return 0 on success */
  2056. static WC_INLINE int IntelRDseed64_r(word64* rnd)
  2057. {
  2058. int i;
  2059. for (i = 0; i < INTELRD_RETRY; i++) {
  2060. if (IntelRDseed64(rnd) == 0)
  2061. return 0;
  2062. }
  2063. return -1;
  2064. }
  2065. #ifndef WOLFSSL_LINUXKM
  2066. /* return 0 on success */
  2067. static int wc_GenerateSeed_IntelRD(OS_Seed* os, byte* output, word32 sz)
  2068. {
  2069. int ret;
  2070. word64 rndTmp;
  2071. (void)os;
  2072. if (!IS_INTEL_RDSEED(intel_flags))
  2073. return -1;
  2074. for (; (sz / sizeof(word64)) > 0; sz -= sizeof(word64),
  2075. output += sizeof(word64)) {
  2076. ret = IntelRDseed64_r((word64*)output);
  2077. if (ret != 0)
  2078. return ret;
  2079. }
  2080. if (sz == 0)
  2081. return 0;
  2082. /* handle unaligned remainder */
  2083. ret = IntelRDseed64_r(&rndTmp);
  2084. if (ret != 0)
  2085. return ret;
  2086. XMEMCPY(output, &rndTmp, sz);
  2087. ForceZero(&rndTmp, sizeof(rndTmp));
  2088. return 0;
  2089. }
  2090. #endif
  2091. #endif /* HAVE_INTEL_RDSEED || HAVE_AMD_RDSEED */
  2092. #ifdef HAVE_INTEL_RDRAND
  2093. #ifndef USE_INTEL_INTRINSICS
  2094. /* return 0 on success */
  2095. static WC_INLINE int IntelRDrand64(word64 *rnd)
  2096. {
  2097. unsigned char ok;
  2098. __asm__ volatile("rdrand %0; setc %1":"=r"(*rnd), "=qm"(ok));
  2099. return (ok) ? 0 : -1;
  2100. }
  2101. #else /* USE_INTEL_INTRINSICS */
  2102. /* The compiler Visual Studio uses does not allow inline assembly.
  2103. * It does allow for Intel intrinsic functions. */
  2104. /* return 0 on success */
  2105. # ifdef __GNUC__
  2106. __attribute__((target("rdrnd")))
  2107. # endif
  2108. static WC_INLINE int IntelRDrand64(word64 *rnd)
  2109. {
  2110. int ok;
  2111. ok = _rdrand64_step((unsigned long long*) rnd);
  2112. return (ok) ? 0 : -1;
  2113. }
  2114. #endif /* USE_INTEL_INTRINSICS */
  2115. /* return 0 on success */
  2116. static WC_INLINE int IntelRDrand64_r(word64 *rnd)
  2117. {
  2118. int i;
  2119. for (i = 0; i < INTELRD_RETRY; i++) {
  2120. if (IntelRDrand64(rnd) == 0)
  2121. return 0;
  2122. }
  2123. return -1;
  2124. }
  2125. /* return 0 on success */
  2126. static int wc_GenerateRand_IntelRD(OS_Seed* os, byte* output, word32 sz)
  2127. {
  2128. int ret;
  2129. word64 rndTmp;
  2130. (void)os;
  2131. if (!IS_INTEL_RDRAND(intel_flags))
  2132. return -1;
  2133. for (; (sz / sizeof(word64)) > 0; sz -= sizeof(word64),
  2134. output += sizeof(word64)) {
  2135. ret = IntelRDrand64_r((word64 *)output);
  2136. if (ret != 0)
  2137. return ret;
  2138. }
  2139. if (sz == 0)
  2140. return 0;
  2141. /* handle unaligned remainder */
  2142. ret = IntelRDrand64_r(&rndTmp);
  2143. if (ret != 0)
  2144. return ret;
  2145. XMEMCPY(output, &rndTmp, sz);
  2146. return 0;
  2147. }
  2148. #endif /* HAVE_INTEL_RDRAND */
  2149. #endif /* HAVE_INTEL_RDRAND || HAVE_INTEL_RDSEED || HAVE_AMD_RDSEED */
  2150. /* Begin wc_GenerateSeed Implementations */
  2151. #if defined(CUSTOM_RAND_GENERATE_SEED)
  2152. /* Implement your own random generation function
  2153. * Return 0 to indicate success
  2154. * int rand_gen_seed(byte* output, word32 sz);
  2155. * #define CUSTOM_RAND_GENERATE_SEED rand_gen_seed */
  2156. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2157. {
  2158. (void)os; /* Suppress unused arg warning */
  2159. return CUSTOM_RAND_GENERATE_SEED(output, sz);
  2160. }
  2161. #elif defined(CUSTOM_RAND_GENERATE_SEED_OS)
  2162. /* Implement your own random generation function,
  2163. * which includes OS_Seed.
  2164. * Return 0 to indicate success
  2165. * int rand_gen_seed(OS_Seed* os, byte* output, word32 sz);
  2166. * #define CUSTOM_RAND_GENERATE_SEED_OS rand_gen_seed */
  2167. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2168. {
  2169. return CUSTOM_RAND_GENERATE_SEED_OS(os, output, sz);
  2170. }
  2171. #elif defined(CUSTOM_RAND_GENERATE)
  2172. /* Implement your own random generation function
  2173. * word32 rand_gen(void);
  2174. * #define CUSTOM_RAND_GENERATE rand_gen */
  2175. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2176. {
  2177. word32 i = 0;
  2178. (void)os;
  2179. while (i < sz)
  2180. {
  2181. /* If not aligned or there is odd/remainder */
  2182. if( (i + sizeof(CUSTOM_RAND_TYPE)) > sz ||
  2183. ((wc_ptr_t)&output[i] % sizeof(CUSTOM_RAND_TYPE)) != 0
  2184. ) {
  2185. /* Single byte at a time */
  2186. output[i++] = (byte)CUSTOM_RAND_GENERATE();
  2187. }
  2188. else {
  2189. /* Use native 8, 16, 32 or 64 copy instruction */
  2190. *((CUSTOM_RAND_TYPE*)&output[i]) = CUSTOM_RAND_GENERATE();
  2191. i += sizeof(CUSTOM_RAND_TYPE);
  2192. }
  2193. }
  2194. return 0;
  2195. }
  2196. #elif defined(WOLFSSL_SGX)
  2197. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2198. {
  2199. int ret = !SGX_SUCCESS;
  2200. int i, read_max = 10;
  2201. for (i = 0; i < read_max && ret != SGX_SUCCESS; i++) {
  2202. ret = sgx_read_rand(output, sz);
  2203. }
  2204. (void)os;
  2205. return (ret == SGX_SUCCESS) ? 0 : 1;
  2206. }
  2207. #elif defined(USE_WINDOWS_API)
  2208. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2209. {
  2210. #ifdef WOLF_CRYPTO_CB
  2211. int ret;
  2212. if (os != NULL
  2213. #ifndef WOLF_CRYPTO_CB_FIND
  2214. && os->devId != INVALID_DEVID)
  2215. #endif
  2216. {
  2217. ret = wc_CryptoCb_RandomSeed(os, output, sz);
  2218. if (ret != CRYPTOCB_UNAVAILABLE)
  2219. return ret;
  2220. /* fall-through when unavailable */
  2221. }
  2222. #endif
  2223. #ifdef HAVE_INTEL_RDSEED
  2224. if (IS_INTEL_RDSEED(intel_flags)) {
  2225. if (!wc_GenerateSeed_IntelRD(NULL, output, sz)) {
  2226. /* success, we're done */
  2227. return 0;
  2228. }
  2229. #ifdef FORCE_FAILURE_RDSEED
  2230. /* don't fall back to CryptoAPI */
  2231. return READ_RAN_E;
  2232. #endif
  2233. }
  2234. #endif /* HAVE_INTEL_RDSEED */
  2235. if(!CryptAcquireContext(&os->handle, 0, 0, PROV_RSA_FULL,
  2236. CRYPT_VERIFYCONTEXT))
  2237. return WINCRYPT_E;
  2238. if (!CryptGenRandom(os->handle, sz, output))
  2239. return CRYPTGEN_E;
  2240. CryptReleaseContext(os->handle, 0);
  2241. return 0;
  2242. }
  2243. #elif defined(HAVE_RTP_SYS) || defined(EBSNET)
  2244. #include "rtprand.h" /* rtp_rand () */
  2245. #include "rtptime.h" /* rtp_get_system_msec() */
  2246. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2247. {
  2248. word32 i;
  2249. rtp_srand(rtp_get_system_msec());
  2250. for (i = 0; i < sz; i++ ) {
  2251. output[i] = rtp_rand() % 256;
  2252. }
  2253. return 0;
  2254. }
  2255. #elif (defined(WOLFSSL_ATMEL) || defined(WOLFSSL_ATECC_RNG)) && \
  2256. !defined(WOLFSSL_PIC32MZ_RNG)
  2257. /* enable ATECC RNG unless using PIC32MZ one instead */
  2258. #include <wolfssl/wolfcrypt/port/atmel/atmel.h>
  2259. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2260. {
  2261. int ret = 0;
  2262. (void)os;
  2263. if (output == NULL) {
  2264. return BUFFER_E;
  2265. }
  2266. ret = atmel_get_random_number(sz, output);
  2267. return ret;
  2268. }
  2269. #elif defined(MICROCHIP_PIC32)
  2270. #ifdef MICROCHIP_MPLAB_HARMONY
  2271. #ifdef MICROCHIP_MPLAB_HARMONY_3
  2272. #include "system/time/sys_time.h"
  2273. #define PIC32_SEED_COUNT SYS_TIME_CounterGet
  2274. #else
  2275. #define PIC32_SEED_COUNT _CP0_GET_COUNT
  2276. #endif
  2277. #else
  2278. #if !defined(WOLFSSL_MICROCHIP_PIC32MZ)
  2279. #include <peripheral/timer.h>
  2280. #endif
  2281. extern word32 ReadCoreTimer(void);
  2282. #define PIC32_SEED_COUNT ReadCoreTimer
  2283. #endif
  2284. #ifdef WOLFSSL_PIC32MZ_RNG
  2285. #include "xc.h"
  2286. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2287. {
  2288. int i;
  2289. byte rnd[8];
  2290. word32 *rnd32 = (word32 *)rnd;
  2291. word32 size = sz;
  2292. byte* op = output;
  2293. #if ((__PIC32_FEATURE_SET0 == 'E') && (__PIC32_FEATURE_SET1 == 'C'))
  2294. RNGNUMGEN1 = _CP0_GET_COUNT();
  2295. RNGPOLY1 = _CP0_GET_COUNT();
  2296. RNGPOLY2 = _CP0_GET_COUNT();
  2297. RNGNUMGEN2 = _CP0_GET_COUNT();
  2298. #else
  2299. /* All others can be seeded from the TRNG */
  2300. RNGCONbits.TRNGMODE = 1;
  2301. RNGCONbits.TRNGEN = 1;
  2302. while (RNGCNT < 64);
  2303. RNGCONbits.LOAD = 1;
  2304. while (RNGCONbits.LOAD == 1);
  2305. while (RNGCNT < 64);
  2306. RNGPOLY2 = RNGSEED2;
  2307. RNGPOLY1 = RNGSEED1;
  2308. #endif
  2309. RNGCONbits.PLEN = 0x40;
  2310. RNGCONbits.PRNGEN = 1;
  2311. for (i=0; i<5; i++) { /* wait for RNGNUMGEN ready */
  2312. volatile int x, y;
  2313. x = RNGNUMGEN1;
  2314. y = RNGNUMGEN2;
  2315. (void)x;
  2316. (void)y;
  2317. }
  2318. do {
  2319. rnd32[0] = RNGNUMGEN1;
  2320. rnd32[1] = RNGNUMGEN2;
  2321. for(i=0; i<8; i++, op++) {
  2322. *op = rnd[i];
  2323. size --;
  2324. if(size==0)break;
  2325. }
  2326. } while(size);
  2327. return 0;
  2328. }
  2329. #else /* WOLFSSL_PIC32MZ_RNG */
  2330. /* uses the core timer, in nanoseconds to seed srand */
  2331. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2332. {
  2333. int i;
  2334. srand(PIC32_SEED_COUNT() * 25);
  2335. for (i = 0; i < sz; i++ ) {
  2336. output[i] = rand() % 256;
  2337. if ( (i % 8) == 7)
  2338. srand(PIC32_SEED_COUNT() * 25);
  2339. }
  2340. return 0;
  2341. }
  2342. #endif /* WOLFSSL_PIC32MZ_RNG */
  2343. #elif defined(FREESCALE_K70_RNGA) || defined(FREESCALE_RNGA)
  2344. /*
  2345. * wc_Generates a RNG seed using the Random Number Generator Accelerator
  2346. * on the Kinetis K70. Documentation located in Chapter 37 of
  2347. * K70 Sub-Family Reference Manual (see Note 3 in the README for link).
  2348. */
  2349. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2350. {
  2351. word32 i;
  2352. /* turn on RNGA module */
  2353. #if defined(SIM_SCGC3_RNGA_MASK)
  2354. SIM_SCGC3 |= SIM_SCGC3_RNGA_MASK;
  2355. #endif
  2356. #if defined(SIM_SCGC6_RNGA_MASK)
  2357. /* additionally needed for at least K64F */
  2358. SIM_SCGC6 |= SIM_SCGC6_RNGA_MASK;
  2359. #endif
  2360. /* set SLP bit to 0 - "RNGA is not in sleep mode" */
  2361. RNG_CR &= ~RNG_CR_SLP_MASK;
  2362. /* set HA bit to 1 - "security violations masked" */
  2363. RNG_CR |= RNG_CR_HA_MASK;
  2364. /* set GO bit to 1 - "output register loaded with data" */
  2365. RNG_CR |= RNG_CR_GO_MASK;
  2366. for (i = 0; i < sz; i++) {
  2367. /* wait for RNG FIFO to be full */
  2368. while((RNG_SR & RNG_SR_OREG_LVL(0xF)) == 0) {}
  2369. /* get value */
  2370. output[i] = RNG_OR;
  2371. }
  2372. return 0;
  2373. }
  2374. #elif defined(FREESCALE_K53_RNGB) || defined(FREESCALE_RNGB)
  2375. /*
  2376. * wc_Generates a RNG seed using the Random Number Generator (RNGB)
  2377. * on the Kinetis K53. Documentation located in Chapter 33 of
  2378. * K53 Sub-Family Reference Manual (see note in the README for link).
  2379. */
  2380. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2381. {
  2382. int i;
  2383. /* turn on RNGB module */
  2384. SIM_SCGC3 |= SIM_SCGC3_RNGB_MASK;
  2385. /* reset RNGB */
  2386. RNG_CMD |= RNG_CMD_SR_MASK;
  2387. /* FIFO generate interrupt, return all zeros on underflow,
  2388. * set auto reseed */
  2389. RNG_CR |= (RNG_CR_FUFMOD_MASK | RNG_CR_AR_MASK);
  2390. /* gen seed, clear interrupts, clear errors */
  2391. RNG_CMD |= (RNG_CMD_GS_MASK | RNG_CMD_CI_MASK | RNG_CMD_CE_MASK);
  2392. /* wait for seeding to complete */
  2393. while ((RNG_SR & RNG_SR_SDN_MASK) == 0) {}
  2394. for (i = 0; i < sz; i++) {
  2395. /* wait for a word to be available from FIFO */
  2396. while((RNG_SR & RNG_SR_FIFO_LVL_MASK) == 0) {}
  2397. /* get value */
  2398. output[i] = RNG_OUT;
  2399. }
  2400. return 0;
  2401. }
  2402. #elif defined(FREESCALE_KSDK_2_0_TRNG)
  2403. #ifndef TRNG0
  2404. #define TRNG0 TRNG
  2405. #endif
  2406. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2407. {
  2408. status_t status;
  2409. status = TRNG_GetRandomData(TRNG0, output, sz);
  2410. (void)os;
  2411. if (status == kStatus_Success)
  2412. {
  2413. return(0);
  2414. }
  2415. return RAN_BLOCK_E;
  2416. }
  2417. #elif defined(FREESCALE_KSDK_2_0_RNGA)
  2418. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2419. {
  2420. status_t status;
  2421. status = RNGA_GetRandomData(RNG, output, sz);
  2422. (void)os;
  2423. if (status == kStatus_Success)
  2424. {
  2425. return(0);
  2426. }
  2427. return RAN_BLOCK_E;
  2428. }
  2429. #elif defined(FREESCALE_RNGA)
  2430. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2431. {
  2432. status_t status;
  2433. status = RNGA_GetRandomData(RNG, output, sz);
  2434. (void)os;
  2435. if (status == kStatus_Success)
  2436. {
  2437. return(0);
  2438. }
  2439. return RAN_BLOCK_E;
  2440. }
  2441. #elif !defined(WOLFSSL_CAAM) && \
  2442. (defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) || \
  2443. defined(FREESCALE_KSDK_BM) || defined(FREESCALE_FREE_RTOS))
  2444. /*
  2445. * Fallback to USE_TEST_GENSEED if a FREESCALE platform did not match any
  2446. * of the TRNG/RNGA/RNGB support
  2447. */
  2448. #define USE_TEST_GENSEED
  2449. #elif defined(WOLFSSL_SILABS_SE_ACCEL)
  2450. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2451. {
  2452. (void)os;
  2453. return silabs_GenerateRand(output, sz);
  2454. }
  2455. #elif defined(STM32_RNG)
  2456. /* Generate a RNG seed using the hardware random number generator
  2457. * on the STM32F2/F4/F7/L4. */
  2458. #ifdef WOLFSSL_STM32_CUBEMX
  2459. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2460. {
  2461. int ret;
  2462. RNG_HandleTypeDef hrng;
  2463. word32 i = 0;
  2464. (void)os;
  2465. ret = wolfSSL_CryptHwMutexLock();
  2466. if (ret != 0) {
  2467. return ret;
  2468. }
  2469. /* enable RNG clock source */
  2470. __HAL_RCC_RNG_CLK_ENABLE();
  2471. /* enable RNG peripheral */
  2472. XMEMSET(&hrng, 0, sizeof(hrng));
  2473. hrng.Instance = RNG;
  2474. HAL_RNG_Init(&hrng);
  2475. while (i < sz) {
  2476. /* If not aligned or there is odd/remainder */
  2477. if( (i + sizeof(word32)) > sz ||
  2478. ((wc_ptr_t)&output[i] % sizeof(word32)) != 0
  2479. ) {
  2480. /* Single byte at a time */
  2481. uint32_t tmpRng = 0;
  2482. if (HAL_RNG_GenerateRandomNumber(&hrng, &tmpRng) != HAL_OK) {
  2483. wolfSSL_CryptHwMutexUnLock();
  2484. return RAN_BLOCK_E;
  2485. }
  2486. output[i++] = (byte)tmpRng;
  2487. }
  2488. else {
  2489. /* Use native 32 instruction */
  2490. if (HAL_RNG_GenerateRandomNumber(&hrng, (uint32_t*)&output[i]) != HAL_OK) {
  2491. wolfSSL_CryptHwMutexUnLock();
  2492. return RAN_BLOCK_E;
  2493. }
  2494. i += sizeof(word32);
  2495. }
  2496. }
  2497. HAL_RNG_DeInit(&hrng);
  2498. wolfSSL_CryptHwMutexUnLock();
  2499. return 0;
  2500. }
  2501. #elif defined(WOLFSSL_STM32F427_RNG) || defined(WOLFSSL_STM32_RNG_NOLIB)
  2502. /* Generate a RNG seed using the hardware RNG on the STM32F427
  2503. * directly, following steps outlined in STM32F4 Reference
  2504. * Manual (Chapter 24) for STM32F4xx family. */
  2505. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2506. {
  2507. int ret;
  2508. word32 i;
  2509. (void)os;
  2510. ret = wolfSSL_CryptHwMutexLock();
  2511. if (ret != 0) {
  2512. return ret;
  2513. }
  2514. /* enable RNG peripheral clock */
  2515. RCC->AHB2ENR |= RCC_AHB2ENR_RNGEN;
  2516. /* enable RNG interrupt, set IE bit in RNG->CR register */
  2517. RNG->CR |= RNG_CR_IE;
  2518. /* enable RNG, set RNGEN bit in RNG->CR. Activates RNG,
  2519. * RNG_LFSR, and error detector */
  2520. RNG->CR |= RNG_CR_RNGEN;
  2521. /* verify no errors, make sure SEIS and CEIS bits are 0
  2522. * in RNG->SR register */
  2523. if (RNG->SR & (RNG_SR_SECS | RNG_SR_CECS)) {
  2524. wolfSSL_CryptHwMutexUnLock();
  2525. return RNG_FAILURE_E;
  2526. }
  2527. for (i = 0; i < sz; i++) {
  2528. /* wait until RNG number is ready */
  2529. while ((RNG->SR & RNG_SR_DRDY) == 0) { }
  2530. /* get value */
  2531. output[i] = RNG->DR;
  2532. }
  2533. wolfSSL_CryptHwMutexUnLock();
  2534. return 0;
  2535. }
  2536. #else
  2537. /* Generate a RNG seed using the STM32 Standard Peripheral Library */
  2538. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2539. {
  2540. int ret;
  2541. word32 i;
  2542. (void)os;
  2543. ret = wolfSSL_CryptHwMutexLock();
  2544. if (ret != 0) {
  2545. return ret;
  2546. }
  2547. /* enable RNG clock source */
  2548. RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_RNG, ENABLE);
  2549. /* reset RNG */
  2550. RNG_DeInit();
  2551. /* enable RNG peripheral */
  2552. RNG_Cmd(ENABLE);
  2553. /* verify no errors with RNG_CLK or Seed */
  2554. if (RNG_GetFlagStatus(RNG_FLAG_SECS | RNG_FLAG_CECS) != RESET) {
  2555. wolfSSL_CryptHwMutexUnLock();
  2556. return RNG_FAILURE_E;
  2557. }
  2558. for (i = 0; i < sz; i++) {
  2559. /* wait until RNG number is ready */
  2560. while (RNG_GetFlagStatus(RNG_FLAG_DRDY) == RESET) { }
  2561. /* get value */
  2562. output[i] = RNG_GetRandomNumber();
  2563. }
  2564. wolfSSL_CryptHwMutexUnLock();
  2565. return 0;
  2566. }
  2567. #endif /* WOLFSSL_STM32_CUBEMX */
  2568. #elif defined(WOLFSSL_TIRTOS)
  2569. #warning "potential for not enough entropy, currently being used for testing"
  2570. #include <xdc/runtime/Timestamp.h>
  2571. #include <stdlib.h>
  2572. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2573. {
  2574. int i;
  2575. srand(xdc_runtime_Timestamp_get32());
  2576. for (i = 0; i < sz; i++ ) {
  2577. output[i] = rand() % 256;
  2578. if ((i % 8) == 7) {
  2579. srand(xdc_runtime_Timestamp_get32());
  2580. }
  2581. }
  2582. return 0;
  2583. }
  2584. #elif defined(WOLFSSL_PB)
  2585. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2586. {
  2587. word32 i;
  2588. for (i = 0; i < sz; i++)
  2589. output[i] = UTL_Rand();
  2590. (void)os;
  2591. return 0;
  2592. }
  2593. #elif defined(WOLFSSL_NUCLEUS)
  2594. #include "nucleus.h"
  2595. #include "kernel/plus_common.h"
  2596. #warning "potential for not enough entropy, currently being used for testing"
  2597. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2598. {
  2599. int i;
  2600. srand(NU_Get_Time_Stamp());
  2601. for (i = 0; i < sz; i++ ) {
  2602. output[i] = rand() % 256;
  2603. if ((i % 8) == 7) {
  2604. srand(NU_Get_Time_Stamp());
  2605. }
  2606. }
  2607. return 0;
  2608. }
  2609. #elif defined(WOLFSSL_DEOS) && !defined(CUSTOM_RAND_GENERATE)
  2610. #include "stdlib.h"
  2611. #warning "potential for not enough entropy, currently being used for testing Deos"
  2612. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2613. {
  2614. int i;
  2615. int seed = XTIME(0);
  2616. (void)os;
  2617. for (i = 0; i < sz; i++ ) {
  2618. output[i] = rand_r(&seed) % 256;
  2619. if ((i % 8) == 7) {
  2620. seed = XTIME(0);
  2621. rand_r(&seed);
  2622. }
  2623. }
  2624. return 0;
  2625. }
  2626. #elif defined(WOLFSSL_VXWORKS)
  2627. #ifdef WOLFSSL_VXWORKS_6_x
  2628. #include "stdlib.h"
  2629. #warning "potential for not enough entropy, currently being used for testing"
  2630. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2631. {
  2632. int i;
  2633. unsigned int seed = (unsigned int)XTIME(0);
  2634. (void)os;
  2635. for (i = 0; i < sz; i++ ) {
  2636. output[i] = rand_r(&seed) % 256;
  2637. if ((i % 8) == 7) {
  2638. seed = (unsigned int)XTIME(0);
  2639. rand_r(&seed);
  2640. }
  2641. }
  2642. return 0;
  2643. }
  2644. #else
  2645. #include <randomNumGen.h>
  2646. #include <tickLib.h>
  2647. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) {
  2648. STATUS status = ERROR;
  2649. RANDOM_NUM_GEN_STATUS r_status = RANDOM_NUM_GEN_ERROR;
  2650. _Vx_ticks_t seed = 0;
  2651. #ifdef VXWORKS_SIM
  2652. /* cannot generate true entropy with VxWorks simulator */
  2653. #warning "not enough entropy, simulator for testing only"
  2654. int i = 0;
  2655. for (i = 0; i < 1000; i++) {
  2656. randomAddTimeStamp();
  2657. }
  2658. #endif
  2659. /*
  2660. wolfSSL can request 52 Bytes of random bytes. We need to add
  2661. buffer to the entropy pool to ensure we can get more than 32 Bytes.
  2662. Because VxWorks has entropy limits (ENTROPY_MIN and ENTROPY_MAX)
  2663. defined as 256 and 1024 bits, see randomSWNumGenLib.c.
  2664. randStatus() can return the following status:
  2665. RANDOM_NUM_GEN_NO_ENTROPY when entropy is 0
  2666. RANDOM_NUM_GEN_ERROR, entropy is not initialized
  2667. RANDOM_NUM_GEN_NOT_ENOUGH_ENTROPY if entropy < 32 Bytes
  2668. RANDOM_NUM_GEN_ENOUGH_ENTROPY if entropy is between 32 and 128 Bytes
  2669. RANDOM_NUM_GEN_MAX_ENTROPY if entropy is greater than 128 Bytes
  2670. */
  2671. do {
  2672. seed = tickGet();
  2673. status = randAdd(&seed, sizeof(_Vx_ticks_t), 2);
  2674. if (status == OK)
  2675. r_status = randStatus();
  2676. } while (r_status != RANDOM_NUM_GEN_MAX_ENTROPY &&
  2677. r_status != RANDOM_NUM_GEN_ERROR && status == OK);
  2678. if (r_status == RANDOM_NUM_GEN_ERROR)
  2679. return RNG_FAILURE_E;
  2680. status = randBytes (output, sz);
  2681. if (status == ERROR) {
  2682. return RNG_FAILURE_E;
  2683. }
  2684. return 0;
  2685. }
  2686. #endif
  2687. #elif defined(WOLFSSL_NRF51) || defined(WOLFSSL_NRF5x)
  2688. #include "app_error.h"
  2689. #include "nrf_drv_rng.h"
  2690. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2691. {
  2692. int remaining = sz, pos = 0;
  2693. word32 err_code;
  2694. byte available;
  2695. static byte initialized = 0;
  2696. (void)os;
  2697. /* Make sure RNG is running */
  2698. if (!initialized) {
  2699. err_code = nrf_drv_rng_init(NULL);
  2700. if (err_code != NRF_SUCCESS && err_code != NRF_ERROR_INVALID_STATE
  2701. #ifdef NRF_ERROR_MODULE_ALREADY_INITIALIZED
  2702. && err_code != NRF_ERROR_MODULE_ALREADY_INITIALIZED
  2703. #endif
  2704. ) {
  2705. return -1;
  2706. }
  2707. initialized = 1;
  2708. }
  2709. while (remaining > 0) {
  2710. int length;
  2711. available = 0;
  2712. nrf_drv_rng_bytes_available(&available); /* void func */
  2713. length = (remaining < available) ? remaining : available;
  2714. if (length > 0) {
  2715. err_code = nrf_drv_rng_rand(&output[pos], length);
  2716. if (err_code != NRF_SUCCESS) {
  2717. break;
  2718. }
  2719. remaining -= length;
  2720. pos += length;
  2721. }
  2722. }
  2723. return (err_code == NRF_SUCCESS) ? 0 : -1;
  2724. }
  2725. #elif defined(HAVE_WNR)
  2726. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2727. {
  2728. if (os == NULL || output == NULL || wnr_ctx == NULL ||
  2729. wnr_timeout < 0) {
  2730. return BAD_FUNC_ARG;
  2731. }
  2732. if (wnr_mutex_init == 0) {
  2733. WOLFSSL_MSG("netRandom context must be created before use");
  2734. return RNG_FAILURE_E;
  2735. }
  2736. if (wc_LockMutex(&wnr_mutex) != 0) {
  2737. WOLFSSL_MSG("Bad Lock Mutex wnr_mutex");
  2738. return BAD_MUTEX_E;
  2739. }
  2740. if (wnr_get_entropy(wnr_ctx, wnr_timeout, output, sz, sz) !=
  2741. WNR_ERROR_NONE)
  2742. return RNG_FAILURE_E;
  2743. wc_UnLockMutex(&wnr_mutex);
  2744. return 0;
  2745. }
  2746. #elif defined(INTIME_RTOS)
  2747. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2748. {
  2749. uint32_t randval;
  2750. word32 len;
  2751. if (output == NULL) {
  2752. return BUFFER_E;
  2753. }
  2754. #ifdef INTIMEVER
  2755. /* If INTIMEVER exists then it is INTIME RTOS v6 or later */
  2756. #define INTIME_RAND_FUNC arc4random
  2757. len = 4;
  2758. #else
  2759. /* v5 and older */
  2760. #define INTIME_RAND_FUNC rand
  2761. srand(time(0));
  2762. len = 2; /* don't use all 31 returned bits */
  2763. #endif
  2764. while (sz > 0) {
  2765. if (sz < len)
  2766. len = sz;
  2767. randval = INTIME_RAND_FUNC();
  2768. XMEMCPY(output, &randval, len);
  2769. output += len;
  2770. sz -= len;
  2771. }
  2772. (void)os;
  2773. return 0;
  2774. }
  2775. #elif defined(WOLFSSL_WICED)
  2776. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2777. {
  2778. int ret;
  2779. (void)os;
  2780. if (output == NULL || UINT16_MAX < sz) {
  2781. return BUFFER_E;
  2782. }
  2783. if ((ret = wiced_crypto_get_random((void*) output, sz) )
  2784. != WICED_SUCCESS) {
  2785. return ret;
  2786. }
  2787. return ret;
  2788. }
  2789. #elif defined(WOLFSSL_NETBURNER)
  2790. #warning using NetBurner pseudo random GetRandomByte for seed
  2791. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2792. {
  2793. word32 i;
  2794. (void)os;
  2795. if (output == NULL) {
  2796. return BUFFER_E;
  2797. }
  2798. for (i = 0; i < sz; i++) {
  2799. output[i] = GetRandomByte();
  2800. /* check if was a valid random number */
  2801. if (!RandomValid())
  2802. return RNG_FAILURE_E;
  2803. }
  2804. return 0;
  2805. }
  2806. #elif defined(IDIRECT_DEV_RANDOM)
  2807. extern int getRandom( int sz, unsigned char *output );
  2808. int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2809. {
  2810. int num_bytes_returned = 0;
  2811. num_bytes_returned = getRandom( (int) sz, (unsigned char *) output );
  2812. return 0;
  2813. }
  2814. #elif defined(WOLFSSL_CAAM)
  2815. #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h>
  2816. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2817. {
  2818. unsigned int args[4] = {0};
  2819. CAAM_BUFFER buf[1];
  2820. int ret = 0;
  2821. int times = 1000, i; /* 1000 is an arbitrary number chosen */
  2822. word32 idx = 0;
  2823. (void)os;
  2824. if (output == NULL) {
  2825. return BUFFER_E;
  2826. }
  2827. /* Check Waiting to make sure entropy is ready */
  2828. for (i = 0; i < times; i++) {
  2829. buf[0].BufferType = DataBuffer | LastBuffer;
  2830. buf[0].TheAddress = (CAAM_ADDRESS)(output + idx);
  2831. buf[0].Length = ((sz - idx) < WC_CAAM_MAX_ENTROPY)?
  2832. sz - idx : WC_CAAM_MAX_ENTROPY;
  2833. args[0] = buf[0].Length;
  2834. ret = wc_caamAddAndWait(buf, 1, args, CAAM_ENTROPY);
  2835. if (ret == 0) {
  2836. idx += buf[0].Length;
  2837. if (idx == sz)
  2838. break;
  2839. }
  2840. /* driver could be waiting for entropy */
  2841. if (ret != RAN_BLOCK_E && ret != 0) {
  2842. return ret;
  2843. }
  2844. #ifndef WOLFSSL_IMXRT1170_CAAM
  2845. usleep(100);
  2846. #endif
  2847. }
  2848. if (i == times && ret != 0) {
  2849. return RNG_FAILURE_E;
  2850. }
  2851. else { /* Success case */
  2852. ret = 0;
  2853. }
  2854. return ret;
  2855. }
  2856. #elif defined(WOLFSSL_APACHE_MYNEWT)
  2857. #include <stdlib.h>
  2858. #include "os/os_time.h"
  2859. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2860. {
  2861. int i;
  2862. srand(os_time_get());
  2863. for (i = 0; i < sz; i++ ) {
  2864. output[i] = rand() % 256;
  2865. if ((i % 8) == 7) {
  2866. srand(os_time_get());
  2867. }
  2868. }
  2869. return 0;
  2870. }
  2871. #elif defined(WOLFSSL_ESPIDF)
  2872. /* Espressif */
  2873. #if defined(WOLFSSL_ESPWROOM32) || defined(WOLFSSL_ESPWROOM32SE)
  2874. /* Espressif ESP32 */
  2875. #include <esp_system.h>
  2876. #if defined(CONFIG_IDF_TARGET_ESP32S3)
  2877. #include <esp_random.h>
  2878. #endif
  2879. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2880. {
  2881. word32 rand;
  2882. while (sz > 0) {
  2883. word32 len = sizeof(rand);
  2884. if (sz < len)
  2885. len = sz;
  2886. /* Get one random 32-bit word from hw RNG */
  2887. rand = esp_random( );
  2888. XMEMCPY(output, &rand, len);
  2889. output += len;
  2890. sz -= len;
  2891. }
  2892. return 0;
  2893. }
  2894. #elif defined(WOLFSSL_ESP8266)
  2895. /* Espressif ESP8266 */
  2896. #include <esp_system.h>
  2897. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2898. {
  2899. word32 rand;
  2900. while (sz > 0) {
  2901. word32 len = sizeof(rand);
  2902. if (sz < len)
  2903. len = sz;
  2904. /* Get one random 32-bit word from hw RNG */
  2905. rand = esp_random( );
  2906. XMEMCPY(output, &rand, len);
  2907. output += len;
  2908. sz -= len;
  2909. }
  2910. return 0;
  2911. }
  2912. #endif /* end WOLFSSL_ESPWROOM32 */
  2913. #elif defined(WOLFSSL_LINUXKM)
  2914. #include <linux/random.h>
  2915. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2916. {
  2917. (void)os;
  2918. get_random_bytes(output, sz);
  2919. return 0;
  2920. }
  2921. #elif defined(WOLFSSL_RENESAS_TSIP)
  2922. #if defined(WOLFSSL_RENESA_TSIP_IAREWRX)
  2923. #include "r_bsp/mcu/all/r_rx_compiler.h"
  2924. #endif
  2925. #include "r_bsp/platform.h"
  2926. #include "r_tsip_rx_if.h"
  2927. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2928. {
  2929. int ret = 0;
  2930. word32 buffer[4];
  2931. while (sz > 0) {
  2932. word32 len = sizeof(buffer);
  2933. if (sz < len) {
  2934. len = sz;
  2935. }
  2936. /* return 4 words random number*/
  2937. ret = R_TSIP_GenerateRandomNumber((uint32_t*)buffer);
  2938. if(ret == TSIP_SUCCESS) {
  2939. XMEMCPY(output, &buffer, len);
  2940. output += len;
  2941. sz -= len;
  2942. } else
  2943. return ret;
  2944. }
  2945. return ret;
  2946. }
  2947. #elif defined(WOLFSSL_RENESAS_SCEPROTECT) || \
  2948. defined(WOLFSSL_RENESAS_SCEPROTECT_CRYPTONLY)
  2949. #include "r_sce.h"
  2950. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2951. {
  2952. int ret = 0;
  2953. word32 buffer[4];
  2954. while (sz > 0) {
  2955. word32 len = sizeof(buffer);
  2956. if (sz < len) {
  2957. len = sz;
  2958. }
  2959. /* return 4 words random number*/
  2960. ret = R_SCE_RandomNumberGenerate(buffer);
  2961. if(ret == FSP_SUCCESS) {
  2962. XMEMCPY(output, &buffer, len);
  2963. output += len;
  2964. sz -= len;
  2965. } else
  2966. return ret;
  2967. }
  2968. return ret;
  2969. }
  2970. #elif defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_TRNG)
  2971. #include "hal_data.h"
  2972. #ifndef WOLFSSL_SCE_TRNG_HANDLE
  2973. #define WOLFSSL_SCE_TRNG_HANDLE g_sce_trng
  2974. #endif
  2975. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2976. {
  2977. word32 ret;
  2978. word32 blocks;
  2979. word32 len = sz;
  2980. ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->open(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl,
  2981. WOLFSSL_SCE_TRNG_HANDLE.p_cfg);
  2982. if (ret != SSP_SUCCESS && ret != SSP_ERR_CRYPTO_ALREADY_OPEN) {
  2983. /* error opening TRNG driver */
  2984. return -1;
  2985. }
  2986. blocks = sz / sizeof(word32);
  2987. if (blocks > 0) {
  2988. ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->read(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl,
  2989. (word32*)output, blocks);
  2990. if (ret != SSP_SUCCESS) {
  2991. return -1;
  2992. }
  2993. }
  2994. len = len - (blocks * sizeof(word32));
  2995. if (len > 0) {
  2996. word32 tmp;
  2997. if (len > sizeof(word32)) {
  2998. return -1;
  2999. }
  3000. ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->read(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl,
  3001. (word32*)&tmp, 1);
  3002. if (ret != SSP_SUCCESS) {
  3003. return -1;
  3004. }
  3005. XMEMCPY(output + (blocks * sizeof(word32)), (byte*)&tmp, len);
  3006. }
  3007. ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->close(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl);
  3008. if (ret != SSP_SUCCESS) {
  3009. /* error opening TRNG driver */
  3010. return -1;
  3011. }
  3012. return 0;
  3013. }
  3014. #elif defined(CUSTOM_RAND_GENERATE_BLOCK)
  3015. /* #define CUSTOM_RAND_GENERATE_BLOCK myRngFunc
  3016. * extern int myRngFunc(byte* output, word32 sz);
  3017. */
  3018. #elif defined(WOLFSSL_SAFERTOS) || defined(WOLFSSL_LEANPSK) || \
  3019. defined(WOLFSSL_IAR_ARM) || defined(WOLFSSL_MDK_ARM) || \
  3020. defined(WOLFSSL_uITRON4) || defined(WOLFSSL_uTKERNEL2) || \
  3021. defined(WOLFSSL_LPC43xx) || defined(NO_STM32_RNG) || \
  3022. defined(MBED) || defined(WOLFSSL_EMBOS) || \
  3023. defined(WOLFSSL_GENSEED_FORTEST) || defined(WOLFSSL_CHIBIOS) || \
  3024. defined(WOLFSSL_CONTIKI) || defined(WOLFSSL_AZSPHERE)
  3025. /* these platforms do not have a default random seed and
  3026. you'll need to implement your own wc_GenerateSeed or define via
  3027. CUSTOM_RAND_GENERATE_BLOCK */
  3028. #define USE_TEST_GENSEED
  3029. #elif defined(WOLFSSL_ZEPHYR)
  3030. #include <zephyr/random/rand32.h>
  3031. #ifndef _POSIX_C_SOURCE
  3032. #include <zephyr/posix/time.h>
  3033. #else
  3034. #include <time.h>
  3035. #endif
  3036. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  3037. {
  3038. sys_rand_get(output, sz);
  3039. return 0;
  3040. }
  3041. #elif defined(WOLFSSL_TELIT_M2MB)
  3042. #include "stdlib.h"
  3043. static long get_timestamp(void) {
  3044. long myTime = 0;
  3045. INT32 fd = m2mb_rtc_open("/dev/rtc0", 0);
  3046. if (fd >= 0) {
  3047. M2MB_RTC_TIMEVAL_T timeval;
  3048. m2mb_rtc_ioctl(fd, M2MB_RTC_IOCTL_GET_TIMEVAL, &timeval);
  3049. myTime = timeval.msec;
  3050. m2mb_rtc_close(fd);
  3051. }
  3052. return myTime;
  3053. }
  3054. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  3055. {
  3056. int i;
  3057. srand(get_timestamp());
  3058. for (i = 0; i < sz; i++ ) {
  3059. output[i] = rand() % 256;
  3060. if ((i % 8) == 7) {
  3061. srand(get_timestamp());
  3062. }
  3063. }
  3064. return 0;
  3065. }
  3066. #elif defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_TRNG)
  3067. #include <wolfssl/wolfcrypt/port/nxp/se050_port.h>
  3068. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz){
  3069. int ret = 0;
  3070. (void)os;
  3071. if (output == NULL) {
  3072. return BUFFER_E;
  3073. }
  3074. ret = wolfSSL_CryptHwMutexLock();
  3075. if (ret == 0) {
  3076. ret = se050_get_random_number(sz, output);
  3077. wolfSSL_CryptHwMutexUnLock();
  3078. }
  3079. return ret;
  3080. }
  3081. #elif defined(DOLPHIN_EMULATOR)
  3082. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  3083. {
  3084. word32 i;
  3085. (void)os;
  3086. srand(time(NULL));
  3087. for (i = 0; i < sz; i++)
  3088. output[i] = (byte)rand();
  3089. return 0;
  3090. }
  3091. #elif defined(WOLFSSL_GETRANDOM)
  3092. /* getrandom() was added to the Linux kernel in version 3.17.
  3093. * Added to glibc in version 2.25. */
  3094. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  3095. {
  3096. int ret = 0;
  3097. (void)os;
  3098. while (sz) {
  3099. int len;
  3100. errno = 0;
  3101. len = (int)getrandom(output, sz, 0);
  3102. if (len == -1) {
  3103. if (errno == EINTR) {
  3104. /* interrupted, call getrandom again */
  3105. continue;
  3106. }
  3107. else {
  3108. ret = READ_RAN_E;
  3109. }
  3110. break;
  3111. }
  3112. sz -= len;
  3113. output += len;
  3114. }
  3115. return ret;
  3116. }
  3117. #elif defined(NO_DEV_RANDOM)
  3118. #error "you need to write an os specific wc_GenerateSeed() here"
  3119. /*
  3120. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  3121. {
  3122. return 0;
  3123. }
  3124. */
  3125. #else
  3126. /* may block */
  3127. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  3128. {
  3129. int ret = 0;
  3130. if (os == NULL) {
  3131. return BAD_FUNC_ARG;
  3132. }
  3133. #ifdef WOLF_CRYPTO_CB
  3134. #ifndef WOLF_CRYPTO_CB_FIND
  3135. if (os->devId != INVALID_DEVID)
  3136. #endif
  3137. {
  3138. ret = wc_CryptoCb_RandomSeed(os, output, sz);
  3139. if (ret != CRYPTOCB_UNAVAILABLE)
  3140. return ret;
  3141. /* fall-through when unavailable */
  3142. ret = 0; /* reset error code */
  3143. }
  3144. #endif
  3145. #ifdef HAVE_ENTROPY_MEMUSE
  3146. ret = wc_Entropy_Get(MAX_ENTROPY_BITS, output, sz);
  3147. if (ret == 0) {
  3148. return 0;
  3149. }
  3150. #ifdef ENTROPY_MEMUSE_FORCE_FAILURE
  3151. /* Don't fallback to /dev/urandom. */
  3152. return ret;
  3153. #endif
  3154. #endif
  3155. #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_AMD_RDSEED)
  3156. if (IS_INTEL_RDSEED(intel_flags)) {
  3157. ret = wc_GenerateSeed_IntelRD(NULL, output, sz);
  3158. if (ret == 0) {
  3159. /* success, we're done */
  3160. return ret;
  3161. }
  3162. #ifdef FORCE_FAILURE_RDSEED
  3163. /* don't fallback to /dev/urandom */
  3164. return ret;
  3165. #else
  3166. /* reset error and fallback to using /dev/urandom */
  3167. ret = 0;
  3168. #endif
  3169. }
  3170. #endif /* HAVE_INTEL_RDSEED || HAVE_AMD_RDSEED */
  3171. #ifndef NO_DEV_URANDOM /* way to disable use of /dev/urandom */
  3172. os->fd = open("/dev/urandom", O_RDONLY);
  3173. if (os->fd == -1)
  3174. #endif
  3175. {
  3176. /* may still have /dev/random */
  3177. os->fd = open("/dev/random", O_RDONLY);
  3178. if (os->fd == -1)
  3179. return OPEN_RAN_E;
  3180. }
  3181. while (sz) {
  3182. int len = (int)read(os->fd, output, sz);
  3183. if (len == -1) {
  3184. ret = READ_RAN_E;
  3185. break;
  3186. }
  3187. sz -= (word32)len;
  3188. output += len;
  3189. if (sz) {
  3190. #if defined(BLOCKING) || defined(WC_RNG_BLOCKING)
  3191. sleep(0); /* context switch */
  3192. #else
  3193. ret = RAN_BLOCK_E;
  3194. break;
  3195. #endif
  3196. }
  3197. }
  3198. close(os->fd);
  3199. return ret;
  3200. }
  3201. #endif
  3202. #ifdef USE_TEST_GENSEED
  3203. #ifndef _MSC_VER
  3204. #warning "write a real random seed!!!!, just for testing now"
  3205. #else
  3206. #pragma message("Warning: write a real random seed!!!!, just for testing now")
  3207. #endif
  3208. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  3209. {
  3210. word32 i;
  3211. for (i = 0; i < sz; i++ )
  3212. output[i] = i;
  3213. (void)os;
  3214. return 0;
  3215. }
  3216. #endif
  3217. /* End wc_GenerateSeed */
  3218. #if defined(CUSTOM_RAND_GENERATE_BLOCK) && defined(WOLFSSL_KCAPI)
  3219. #include <fcntl.h>
  3220. int wc_hwrng_generate_block(byte *output, word32 sz)
  3221. {
  3222. int fd;
  3223. int ret = 0;
  3224. fd = open("/dev/hwrng", O_RDONLY);
  3225. if (fd == -1)
  3226. return OPEN_RAN_E;
  3227. while(sz)
  3228. {
  3229. int len = (int)read(fd, output, sz);
  3230. if (len == -1)
  3231. {
  3232. ret = READ_RAN_E;
  3233. break;
  3234. }
  3235. sz -= len;
  3236. output += len;
  3237. }
  3238. close(fd);
  3239. return ret;
  3240. }
  3241. #endif
  3242. #endif /* WC_NO_RNG */
  3243. #endif /* HAVE_FIPS */