random.c 105 KB

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