random.c 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691
  1. /* random.c
  2. *
  3. * Copyright (C) 2006-2021 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(HAVE_FIPS) && \
  34. defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)
  35. /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */
  36. #define FIPS_NO_WRAPPERS
  37. #ifdef USE_WINDOWS_API
  38. #pragma code_seg(".fipsA$c")
  39. #pragma const_seg(".fipsB$c")
  40. #endif
  41. #endif
  42. #include <wolfssl/wolfcrypt/random.h>
  43. #include <wolfssl/wolfcrypt/cpuid.h>
  44. /* If building for old FIPS. */
  45. #if defined(HAVE_FIPS) && \
  46. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2))
  47. int wc_GenerateSeed(OS_Seed* os, byte* seed, word32 sz)
  48. {
  49. return GenerateSeed(os, seed, sz);
  50. }
  51. int wc_InitRng_ex(WC_RNG* rng, void* heap, int devId)
  52. {
  53. (void)heap;
  54. (void)devId;
  55. return InitRng_fips(rng);
  56. }
  57. int wc_InitRng(WC_RNG* rng)
  58. {
  59. return InitRng_fips(rng);
  60. }
  61. int wc_RNG_GenerateBlock(WC_RNG* rng, byte* b, word32 sz)
  62. {
  63. return RNG_GenerateBlock_fips(rng, b, sz);
  64. }
  65. int wc_RNG_GenerateByte(WC_RNG* rng, byte* b)
  66. {
  67. return RNG_GenerateByte(rng, b);
  68. }
  69. #ifdef HAVE_HASHDRBG
  70. int wc_FreeRng(WC_RNG* rng)
  71. {
  72. return FreeRng_fips(rng);
  73. }
  74. int wc_RNG_HealthTest(int reseed, const byte* seedA, word32 seedASz,
  75. const byte* seedB, word32 seedBSz,
  76. byte* output, word32 outputSz)
  77. {
  78. return RNG_HealthTest_fips(reseed, seedA, seedASz,
  79. seedB, seedBSz, output, outputSz);
  80. }
  81. #endif /* HAVE_HASHDRBG */
  82. #else /* else build without fips, or for new fips */
  83. #ifndef WC_NO_RNG /* if not FIPS and RNG is disabled then do not compile */
  84. #include <wolfssl/wolfcrypt/sha256.h>
  85. #ifdef WOLF_CRYPTO_CB
  86. #include <wolfssl/wolfcrypt/cryptocb.h>
  87. #endif
  88. #ifdef NO_INLINE
  89. #include <wolfssl/wolfcrypt/misc.h>
  90. #else
  91. #define WOLFSSL_MISC_INCLUDED
  92. #include <wolfcrypt/src/misc.c>
  93. #endif
  94. #if defined(WOLFSSL_SGX)
  95. #include <sgx_trts.h>
  96. #elif defined(USE_WINDOWS_API)
  97. #ifndef _WIN32_WINNT
  98. #define _WIN32_WINNT 0x0400
  99. #endif
  100. #include <windows.h>
  101. #include <wincrypt.h>
  102. #elif defined(HAVE_WNR)
  103. #include <wnr.h>
  104. #include <wolfssl/wolfcrypt/logging.h>
  105. wolfSSL_Mutex wnr_mutex; /* global netRandom mutex */
  106. int wnr_timeout = 0; /* entropy timeout, mililseconds */
  107. int wnr_mutex_init = 0; /* flag for mutex init */
  108. wnr_context* wnr_ctx; /* global netRandom context */
  109. #elif defined(FREESCALE_KSDK_2_0_TRNG)
  110. #include "fsl_trng.h"
  111. #elif defined(FREESCALE_KSDK_2_0_RNGA)
  112. #include "fsl_rnga.h"
  113. #elif defined(WOLFSSL_WICED)
  114. #include "wiced_crypto.h"
  115. #elif defined(WOLFSSL_NETBURNER)
  116. #include <predef.h>
  117. #include <basictypes.h>
  118. #include <random.h>
  119. #elif defined(NO_DEV_RANDOM)
  120. #elif defined(CUSTOM_RAND_GENERATE)
  121. #elif defined(CUSTOM_RAND_GENERATE_BLOCK)
  122. #elif defined(CUSTOM_RAND_GENERATE_SEED)
  123. #elif defined(WOLFSSL_GENSEED_FORTEST)
  124. #elif defined(WOLFSSL_MDK_ARM)
  125. #elif defined(WOLFSSL_IAR_ARM)
  126. #elif defined(WOLFSSL_ROWLEY_ARM)
  127. #elif defined(WOLFSSL_EMBOS)
  128. #elif defined(WOLFSSL_DEOS)
  129. #elif defined(MICRIUM)
  130. #elif defined(WOLFSSL_NUCLEUS)
  131. #elif defined(WOLFSSL_PB)
  132. #elif defined(WOLFSSL_ZEPHYR)
  133. #elif defined(WOLFSSL_TELIT_M2MB)
  134. #elif defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_TRNG)
  135. #else
  136. /* include headers that may be needed to get good seed */
  137. #include <fcntl.h>
  138. #ifndef EBSNET
  139. #include <unistd.h>
  140. #endif
  141. #endif
  142. #if defined(WOLFSSL_SILABS_SE_ACCEL)
  143. #include <wolfssl/wolfcrypt/port/silabs/silabs_random.h>
  144. #endif
  145. #if defined(HAVE_INTEL_RDRAND) || defined(HAVE_INTEL_RDSEED)
  146. static word32 intel_flags = 0;
  147. static void wc_InitRng_IntelRD(void)
  148. {
  149. intel_flags = cpuid_get_flags();
  150. }
  151. #if defined(HAVE_INTEL_RDSEED) && !defined(WOLFSSL_LINUXKM)
  152. static int wc_GenerateSeed_IntelRD(OS_Seed* os, byte* output, word32 sz);
  153. #endif
  154. #ifdef HAVE_INTEL_RDRAND
  155. static int wc_GenerateRand_IntelRD(OS_Seed* os, byte* output, word32 sz);
  156. #endif
  157. #ifdef USE_WINDOWS_API
  158. #define USE_INTEL_INTRINSICS
  159. #elif !defined __GNUC__ || defined __clang__ || __GNUC__ > 4
  160. #define USE_INTEL_INTRINSICS
  161. #else
  162. #undef USE_INTEL_INTRINSICS
  163. #endif
  164. #ifdef USE_INTEL_INTRINSICS
  165. #include <immintrin.h>
  166. /* Before clang 7 or GCC 9, immintrin.h did not define _rdseed64_step() */
  167. #ifndef HAVE_INTEL_RDSEED
  168. #elif defined __clang__ && __clang_major__ > 6
  169. #elif !defined __GNUC__
  170. #elif __GNUC__ > 8
  171. #else
  172. #ifndef __clang__
  173. #pragma GCC push_options
  174. #pragma GCC target("rdseed")
  175. #else
  176. #define __RDSEED__
  177. #endif
  178. #include <x86intrin.h>
  179. #ifndef __clang__
  180. #pragma GCC pop_options
  181. #endif
  182. #endif
  183. #endif /* USE_WINDOWS_API */
  184. #endif
  185. /* Start NIST DRBG code */
  186. #ifdef HAVE_HASHDRBG
  187. #define OUTPUT_BLOCK_LEN (WC_SHA256_DIGEST_SIZE)
  188. #define MAX_REQUEST_LEN (0x10000)
  189. #define RESEED_INTERVAL WC_RESEED_INTERVAL
  190. /* For FIPS builds, the user should not be adjusting the values. */
  191. #if defined(HAVE_FIPS) && \
  192. defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)
  193. #if defined(RNG_SECURITY_STRENGTH) \
  194. || defined(ENTROPY_SCALE_FACTOR) \
  195. || defined(SEED_BLOCK_SZ)
  196. #error "Do not change the RNG parameters for FIPS builds."
  197. #endif
  198. #endif
  199. /* The security strength for the RNG is the target number of bits of
  200. * entropy you are looking for in a seed. */
  201. #ifndef RNG_SECURITY_STRENGTH
  202. #if defined(HAVE_FIPS) && \
  203. defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)
  204. /* SHA-256 requires a minimum of 256-bits of entropy. The goal
  205. * of 1024 will provide 4 times that. */
  206. #define RNG_SECURITY_STRENGTH (1024)
  207. #else
  208. /* If not using FIPS or using old FIPS, set the number down a bit.
  209. * More is better, but more is also slower. */
  210. #define RNG_SECURITY_STRENGTH (256)
  211. #endif
  212. #endif
  213. #ifndef ENTROPY_SCALE_FACTOR
  214. /* The entropy scale factor should be the whole number inverse of the
  215. * minimum bits of entropy per bit of NDRNG output. */
  216. #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND)
  217. /* The value of 2 applies to Intel's RDSEED which provides about
  218. * 0.5 bits minimum of entropy per bit. */
  219. #define ENTROPY_SCALE_FACTOR 2
  220. #else
  221. /* Setting the default to 1. */
  222. #define ENTROPY_SCALE_FACTOR 1
  223. #endif
  224. #endif
  225. #ifndef SEED_BLOCK_SZ
  226. /* The seed block size, is the size of the output of the underlying NDRNG.
  227. * This value is used for testing the output of the NDRNG. */
  228. #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND)
  229. /* RDSEED outputs in blocks of 64-bits. */
  230. #define SEED_BLOCK_SZ sizeof(word64)
  231. #else
  232. /* Setting the default to 4. */
  233. #define SEED_BLOCK_SZ 4
  234. #endif
  235. #endif
  236. #define SEED_SZ (RNG_SECURITY_STRENGTH*ENTROPY_SCALE_FACTOR/8)
  237. /* The maximum seed size will be the seed size plus a seed block for the
  238. * test, and an additional half of the seed size. This additional half
  239. * is in case the user does not supply a nonce. A nonce will be obtained
  240. * from the NDRNG. */
  241. #define MAX_SEED_SZ (SEED_SZ + SEED_SZ/2 + SEED_BLOCK_SZ)
  242. /* Internal return codes */
  243. #define DRBG_SUCCESS 0
  244. #define DRBG_FAILURE 1
  245. #define DRBG_NEED_RESEED 2
  246. #define DRBG_CONT_FAILURE 3
  247. /* RNG health states */
  248. #define DRBG_NOT_INIT 0
  249. #define DRBG_OK 1
  250. #define DRBG_FAILED 2
  251. #define DRBG_CONT_FAILED 3
  252. #define RNG_HEALTH_TEST_CHECK_SIZE (WC_SHA256_DIGEST_SIZE * 4)
  253. /* Verify max gen block len */
  254. #if RNG_MAX_BLOCK_LEN > MAX_REQUEST_LEN
  255. #error RNG_MAX_BLOCK_LEN is larger than NIST DBRG max request length
  256. #endif
  257. enum {
  258. drbgInitC = 0,
  259. drbgReseed = 1,
  260. drbgGenerateW = 2,
  261. drbgGenerateH = 3,
  262. drbgInitV = 4
  263. };
  264. typedef struct DRBG_internal DRBG_internal;
  265. static int wc_RNG_HealthTestLocal(int reseed);
  266. /* Hash Derivation Function */
  267. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  268. static int Hash_df(DRBG_internal* drbg, byte* out, word32 outSz, byte type,
  269. const byte* inA, word32 inASz,
  270. const byte* inB, word32 inBSz)
  271. {
  272. int ret = DRBG_FAILURE;
  273. byte ctr;
  274. int i;
  275. int len;
  276. word32 bits = (outSz * 8); /* reverse byte order */
  277. #ifdef WOLFSSL_SMALL_STACK_CACHE
  278. wc_Sha256* sha = &drbg->sha256;
  279. #else
  280. wc_Sha256 sha[1];
  281. #endif
  282. #ifdef WC_ASYNC_ENABLE_SHA256
  283. DECLARE_VAR(digest, byte, WC_SHA256_DIGEST_SIZE, drbg->heap);
  284. if (digest == NULL)
  285. return MEMORY_E;
  286. #else
  287. byte digest[WC_SHA256_DIGEST_SIZE];
  288. #endif
  289. (void)drbg;
  290. #ifdef WC_ASYNC_ENABLE_SHA256
  291. if (digest == NULL)
  292. return DRBG_FAILURE;
  293. #endif
  294. #ifdef LITTLE_ENDIAN_ORDER
  295. bits = ByteReverseWord32(bits);
  296. #endif
  297. len = (outSz / OUTPUT_BLOCK_LEN)
  298. + ((outSz % OUTPUT_BLOCK_LEN) ? 1 : 0);
  299. ctr = 1;
  300. for (i = 0; i < len; i++) {
  301. #ifndef WOLFSSL_SMALL_STACK_CACHE
  302. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
  303. ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId);
  304. #else
  305. ret = wc_InitSha256(sha);
  306. #endif
  307. if (ret != 0)
  308. break;
  309. #endif
  310. ret = wc_Sha256Update(sha, &ctr, sizeof(ctr));
  311. if (ret == 0) {
  312. ctr++;
  313. ret = wc_Sha256Update(sha, (byte*)&bits, sizeof(bits));
  314. }
  315. if (ret == 0) {
  316. /* churning V is the only string that doesn't have the type added */
  317. if (type != drbgInitV)
  318. ret = wc_Sha256Update(sha, &type, sizeof(type));
  319. }
  320. if (ret == 0)
  321. ret = wc_Sha256Update(sha, inA, inASz);
  322. if (ret == 0) {
  323. if (inB != NULL && inBSz > 0)
  324. ret = wc_Sha256Update(sha, inB, inBSz);
  325. }
  326. if (ret == 0)
  327. ret = wc_Sha256Final(sha, digest);
  328. #ifndef WOLFSSL_SMALL_STACK_CACHE
  329. wc_Sha256Free(sha);
  330. #endif
  331. if (ret == 0) {
  332. if (outSz > OUTPUT_BLOCK_LEN) {
  333. XMEMCPY(out, digest, OUTPUT_BLOCK_LEN);
  334. outSz -= OUTPUT_BLOCK_LEN;
  335. out += OUTPUT_BLOCK_LEN;
  336. }
  337. else {
  338. XMEMCPY(out, digest, outSz);
  339. }
  340. }
  341. }
  342. ForceZero(digest, WC_SHA256_DIGEST_SIZE);
  343. #ifdef WC_ASYNC_ENABLE_SHA256
  344. FREE_VAR(digest, drbg->heap);
  345. #endif
  346. return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
  347. }
  348. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  349. static int Hash_DRBG_Reseed(DRBG_internal* drbg, const byte* seed, word32 seedSz)
  350. {
  351. byte newV[DRBG_SEED_LEN];
  352. XMEMSET(newV, 0, DRBG_SEED_LEN);
  353. if (Hash_df(drbg, newV, sizeof(newV), drbgReseed,
  354. drbg->V, sizeof(drbg->V), seed, seedSz) != DRBG_SUCCESS) {
  355. return DRBG_FAILURE;
  356. }
  357. XMEMCPY(drbg->V, newV, sizeof(drbg->V));
  358. ForceZero(newV, sizeof(newV));
  359. if (Hash_df(drbg, drbg->C, sizeof(drbg->C), drbgInitC, drbg->V,
  360. sizeof(drbg->V), NULL, 0) != DRBG_SUCCESS) {
  361. return DRBG_FAILURE;
  362. }
  363. drbg->reseedCtr = 1;
  364. drbg->lastBlock = 0;
  365. drbg->matchCount = 0;
  366. return DRBG_SUCCESS;
  367. }
  368. /* Returns: DRBG_SUCCESS and DRBG_FAILURE or BAD_FUNC_ARG on fail */
  369. int wc_RNG_DRBG_Reseed(WC_RNG* rng, const byte* seed, word32 seedSz)
  370. {
  371. if (rng == NULL || seed == NULL) {
  372. return BAD_FUNC_ARG;
  373. }
  374. return Hash_DRBG_Reseed((DRBG_internal *)rng->drbg, seed, seedSz);
  375. }
  376. static WC_INLINE void array_add_one(byte* data, word32 dataSz)
  377. {
  378. int i;
  379. for (i = dataSz - 1; i >= 0; i--)
  380. {
  381. data[i]++;
  382. if (data[i] != 0) break;
  383. }
  384. }
  385. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  386. static int Hash_gen(DRBG_internal* drbg, byte* out, word32 outSz, const byte* V)
  387. {
  388. int ret = DRBG_FAILURE;
  389. byte data[DRBG_SEED_LEN];
  390. int i;
  391. int len;
  392. word32 checkBlock;
  393. #ifdef WOLFSSL_SMALL_STACK_CACHE
  394. wc_Sha256* sha = &drbg->sha256;
  395. #else
  396. wc_Sha256 sha[1];
  397. #endif
  398. #ifdef WC_ASYNC_ENABLE_SHA256
  399. DECLARE_VAR(digest, byte, WC_SHA256_DIGEST_SIZE, drbg->heap);
  400. if (digest == NULL)
  401. return MEMORY_E;
  402. #else
  403. byte digest[WC_SHA256_DIGEST_SIZE];
  404. #endif
  405. /* Special case: outSz is 0 and out is NULL. wc_Generate a block to save for
  406. * the continuous test. */
  407. if (outSz == 0) outSz = 1;
  408. len = (outSz / OUTPUT_BLOCK_LEN) + ((outSz % OUTPUT_BLOCK_LEN) ? 1 : 0);
  409. XMEMCPY(data, V, sizeof(data));
  410. for (i = 0; i < len; i++) {
  411. #ifndef WOLFSSL_SMALL_STACK_CACHE
  412. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
  413. ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId);
  414. #else
  415. ret = wc_InitSha256(sha);
  416. #endif
  417. if (ret == 0)
  418. #endif
  419. ret = wc_Sha256Update(sha, data, sizeof(data));
  420. if (ret == 0)
  421. ret = wc_Sha256Final(sha, digest);
  422. #ifndef WOLFSSL_SMALL_STACK_CACHE
  423. wc_Sha256Free(sha);
  424. #endif
  425. if (ret == 0) {
  426. XMEMCPY(&checkBlock, digest, sizeof(word32));
  427. if (drbg->reseedCtr > 1 && checkBlock == drbg->lastBlock) {
  428. if (drbg->matchCount == 1) {
  429. return DRBG_CONT_FAILURE;
  430. }
  431. else {
  432. if (i == (len-1)) {
  433. len++;
  434. }
  435. drbg->matchCount = 1;
  436. }
  437. }
  438. else {
  439. drbg->matchCount = 0;
  440. drbg->lastBlock = checkBlock;
  441. }
  442. if (out != NULL && outSz != 0) {
  443. if (outSz >= OUTPUT_BLOCK_LEN) {
  444. XMEMCPY(out, digest, OUTPUT_BLOCK_LEN);
  445. outSz -= OUTPUT_BLOCK_LEN;
  446. out += OUTPUT_BLOCK_LEN;
  447. array_add_one(data, DRBG_SEED_LEN);
  448. }
  449. else {
  450. XMEMCPY(out, digest, outSz);
  451. outSz = 0;
  452. }
  453. }
  454. }
  455. else {
  456. /* wc_Sha256Update or wc_Sha256Final returned error */
  457. break;
  458. }
  459. }
  460. ForceZero(data, sizeof(data));
  461. #ifdef WC_ASYNC_ENABLE_SHA256
  462. FREE_VAR(digest, drbg->heap);
  463. #endif
  464. return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
  465. }
  466. static WC_INLINE void array_add(byte* d, word32 dLen, const byte* s, word32 sLen)
  467. {
  468. word16 carry = 0;
  469. if (dLen > 0 && sLen > 0 && dLen >= sLen) {
  470. int sIdx, dIdx;
  471. dIdx = dLen - 1;
  472. for (sIdx = sLen - 1; sIdx >= 0; sIdx--) {
  473. carry += (word16)d[dIdx] + (word16)s[sIdx];
  474. d[dIdx] = (byte)carry;
  475. carry >>= 8;
  476. dIdx--;
  477. }
  478. for (; carry != 0 && dIdx >= 0; dIdx--) {
  479. carry += (word16)d[dIdx];
  480. d[dIdx] = (byte)carry;
  481. carry >>= 8;
  482. }
  483. }
  484. }
  485. /* Returns: DRBG_SUCCESS, DRBG_NEED_RESEED, or DRBG_FAILURE */
  486. static int Hash_DRBG_Generate(DRBG_internal* drbg, byte* out, word32 outSz)
  487. {
  488. int ret;
  489. #ifdef WOLFSSL_SMALL_STACK_CACHE
  490. wc_Sha256* sha = &drbg->sha256;
  491. #else
  492. wc_Sha256 sha[1];
  493. #endif
  494. byte type;
  495. word32 reseedCtr;
  496. if (drbg->reseedCtr == RESEED_INTERVAL) {
  497. return DRBG_NEED_RESEED;
  498. } else {
  499. #ifdef WC_ASYNC_ENABLE_SHA256
  500. DECLARE_VAR(digest, byte, WC_SHA256_DIGEST_SIZE, drbg->heap);
  501. if (digest == NULL)
  502. return MEMORY_E;
  503. #else
  504. byte digest[WC_SHA256_DIGEST_SIZE];
  505. #endif
  506. type = drbgGenerateH;
  507. reseedCtr = drbg->reseedCtr;
  508. ret = Hash_gen(drbg, out, outSz, drbg->V);
  509. if (ret == DRBG_SUCCESS) {
  510. #ifndef WOLFSSL_SMALL_STACK_CACHE
  511. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
  512. ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId);
  513. #else
  514. ret = wc_InitSha256(sha);
  515. #endif
  516. if (ret == 0)
  517. #endif
  518. ret = wc_Sha256Update(sha, &type, sizeof(type));
  519. if (ret == 0)
  520. ret = wc_Sha256Update(sha, drbg->V, sizeof(drbg->V));
  521. if (ret == 0)
  522. ret = wc_Sha256Final(sha, digest);
  523. #ifndef WOLFSSL_SMALL_STACK_CACHE
  524. wc_Sha256Free(sha);
  525. #endif
  526. if (ret == 0) {
  527. array_add(drbg->V, sizeof(drbg->V), digest, WC_SHA256_DIGEST_SIZE);
  528. array_add(drbg->V, sizeof(drbg->V), drbg->C, sizeof(drbg->C));
  529. #ifdef LITTLE_ENDIAN_ORDER
  530. reseedCtr = ByteReverseWord32(reseedCtr);
  531. #endif
  532. array_add(drbg->V, sizeof(drbg->V),
  533. (byte*)&reseedCtr, sizeof(reseedCtr));
  534. ret = DRBG_SUCCESS;
  535. }
  536. drbg->reseedCtr++;
  537. }
  538. ForceZero(digest, WC_SHA256_DIGEST_SIZE);
  539. #ifdef WC_ASYNC_ENABLE_SHA256
  540. FREE_VAR(digest, drbg->heap);
  541. #endif
  542. }
  543. return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
  544. }
  545. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  546. static int Hash_DRBG_Instantiate(DRBG_internal* drbg, const byte* seed, word32 seedSz,
  547. const byte* nonce, word32 nonceSz,
  548. void* heap, int devId)
  549. {
  550. int ret = DRBG_FAILURE;
  551. XMEMSET(drbg, 0, sizeof(DRBG_internal));
  552. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
  553. drbg->heap = heap;
  554. drbg->devId = devId;
  555. #else
  556. (void)heap;
  557. (void)devId;
  558. #endif
  559. #ifdef WOLFSSL_SMALL_STACK_CACHE
  560. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
  561. ret = wc_InitSha256_ex(&drbg->sha256, drbg->heap, drbg->devId);
  562. #else
  563. ret = wc_InitSha256(&drbg->sha256);
  564. #endif
  565. if (ret != 0)
  566. return ret;
  567. #endif
  568. if (Hash_df(drbg, drbg->V, sizeof(drbg->V), drbgInitV, seed, seedSz,
  569. nonce, nonceSz) == DRBG_SUCCESS &&
  570. Hash_df(drbg, drbg->C, sizeof(drbg->C), drbgInitC, drbg->V,
  571. sizeof(drbg->V), NULL, 0) == DRBG_SUCCESS) {
  572. drbg->reseedCtr = 1;
  573. drbg->lastBlock = 0;
  574. drbg->matchCount = 0;
  575. ret = DRBG_SUCCESS;
  576. }
  577. return ret;
  578. }
  579. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  580. static int Hash_DRBG_Uninstantiate(DRBG_internal* drbg)
  581. {
  582. word32 i;
  583. int compareSum = 0;
  584. byte* compareDrbg = (byte*)drbg;
  585. #ifdef WOLFSSL_SMALL_STACK_CACHE
  586. wc_Sha256Free(&drbg->sha256);
  587. #endif
  588. ForceZero(drbg, sizeof(DRBG_internal));
  589. for (i = 0; i < sizeof(DRBG_internal); i++)
  590. compareSum |= compareDrbg[i] ^ 0;
  591. return (compareSum == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
  592. }
  593. int wc_RNG_TestSeed(const byte* seed, word32 seedSz)
  594. {
  595. int ret = 0;
  596. /* Check the seed for duplicate words. */
  597. word32 seedIdx = 0;
  598. word32 scratchSz = min(SEED_BLOCK_SZ, seedSz - SEED_BLOCK_SZ);
  599. while (seedIdx < seedSz - SEED_BLOCK_SZ) {
  600. if (ConstantCompare(seed + seedIdx,
  601. seed + seedIdx + scratchSz,
  602. scratchSz) == 0) {
  603. ret = DRBG_CONT_FAILURE;
  604. }
  605. seedIdx += SEED_BLOCK_SZ;
  606. scratchSz = min(SEED_BLOCK_SZ, (seedSz - seedIdx));
  607. }
  608. return ret;
  609. }
  610. #endif /* HAVE_HASHDRBG */
  611. /* End NIST DRBG Code */
  612. static int _InitRng(WC_RNG* rng, byte* nonce, word32 nonceSz,
  613. void* heap, int devId)
  614. {
  615. int ret = 0;
  616. #ifdef HAVE_HASHDRBG
  617. word32 seedSz = SEED_SZ + SEED_BLOCK_SZ;
  618. #endif
  619. (void)nonce;
  620. (void)nonceSz;
  621. if (rng == NULL)
  622. return BAD_FUNC_ARG;
  623. if (nonce == NULL && nonceSz != 0)
  624. return BAD_FUNC_ARG;
  625. #ifdef WOLFSSL_HEAP_TEST
  626. rng->heap = (void*)WOLFSSL_HEAP_TEST;
  627. (void)heap;
  628. #else
  629. rng->heap = heap;
  630. #endif
  631. #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
  632. rng->devId = devId;
  633. #if defined(WOLF_CRYPTO_CB)
  634. rng->seed.devId = devId;
  635. #endif
  636. #else
  637. (void)devId;
  638. #endif
  639. #ifdef HAVE_HASHDRBG
  640. /* init the DBRG to known values */
  641. rng->drbg = NULL;
  642. rng->status = DRBG_NOT_INIT;
  643. #endif
  644. #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND)
  645. /* init the intel RD seed and/or rand */
  646. wc_InitRng_IntelRD();
  647. #endif
  648. /* configure async RNG source if available */
  649. #ifdef WOLFSSL_ASYNC_CRYPT
  650. ret = wolfAsync_DevCtxInit(&rng->asyncDev, WOLFSSL_ASYNC_MARKER_RNG,
  651. rng->heap, rng->devId);
  652. if (ret != 0)
  653. return ret;
  654. #endif
  655. #ifdef HAVE_INTEL_RDRAND
  656. /* if CPU supports RDRAND, use it directly and by-pass DRBG init */
  657. if (IS_INTEL_RDRAND(intel_flags))
  658. return 0;
  659. #endif
  660. #ifdef CUSTOM_RAND_GENERATE_BLOCK
  661. ret = 0; /* success */
  662. #else
  663. #ifdef HAVE_HASHDRBG
  664. if (nonceSz == 0)
  665. seedSz = MAX_SEED_SZ;
  666. if (wc_RNG_HealthTestLocal(0) == 0) {
  667. #ifdef WC_ASYNC_ENABLE_SHA256
  668. DECLARE_VAR(seed, byte, MAX_SEED_SZ, rng->heap);
  669. if (seed == NULL)
  670. return MEMORY_E;
  671. #else
  672. byte seed[MAX_SEED_SZ];
  673. #endif
  674. #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
  675. rng->drbg =
  676. (struct DRBG*)XMALLOC(sizeof(DRBG_internal), rng->heap,
  677. DYNAMIC_TYPE_RNG);
  678. if (rng->drbg == NULL) {
  679. ret = MEMORY_E;
  680. rng->status = DRBG_FAILED;
  681. }
  682. #else
  683. rng->drbg = (struct DRBG*)&rng->drbg_data;
  684. #endif
  685. if (ret == 0) {
  686. ret = wc_GenerateSeed(&rng->seed, seed, seedSz);
  687. if (ret == 0)
  688. ret = wc_RNG_TestSeed(seed, seedSz);
  689. else {
  690. ret = DRBG_FAILURE;
  691. rng->status = DRBG_FAILED;
  692. }
  693. if (ret == DRBG_SUCCESS)
  694. ret = Hash_DRBG_Instantiate((DRBG_internal *)rng->drbg,
  695. seed + SEED_BLOCK_SZ, seedSz - SEED_BLOCK_SZ,
  696. nonce, nonceSz, rng->heap, devId);
  697. if (ret != DRBG_SUCCESS) {
  698. #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
  699. XFREE(rng->drbg, rng->heap, DYNAMIC_TYPE_RNG);
  700. #endif
  701. rng->drbg = NULL;
  702. }
  703. }
  704. ForceZero(seed, seedSz);
  705. #ifdef WC_ASYNC_ENABLE_SHA256
  706. FREE_VAR(seed, rng->heap);
  707. #endif
  708. }
  709. else
  710. ret = DRBG_CONT_FAILURE;
  711. if (ret == DRBG_SUCCESS) {
  712. rng->status = DRBG_OK;
  713. ret = 0;
  714. }
  715. else if (ret == DRBG_CONT_FAILURE) {
  716. rng->status = DRBG_CONT_FAILED;
  717. ret = DRBG_CONT_FIPS_E;
  718. }
  719. else if (ret == DRBG_FAILURE) {
  720. rng->status = DRBG_FAILED;
  721. ret = RNG_FAILURE_E;
  722. }
  723. else {
  724. rng->status = DRBG_FAILED;
  725. }
  726. #endif /* HAVE_HASHDRBG */
  727. #endif /* CUSTOM_RAND_GENERATE_BLOCK */
  728. return ret;
  729. }
  730. WOLFSSL_ABI
  731. WC_RNG* wc_rng_new(byte* nonce, word32 nonceSz, void* heap)
  732. {
  733. WC_RNG* rng;
  734. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), heap, DYNAMIC_TYPE_RNG);
  735. if (rng) {
  736. int error = _InitRng(rng, nonce, nonceSz, heap, INVALID_DEVID) != 0;
  737. if (error) {
  738. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  739. rng = NULL;
  740. }
  741. }
  742. return rng;
  743. }
  744. WOLFSSL_ABI
  745. void wc_rng_free(WC_RNG* rng)
  746. {
  747. if (rng) {
  748. void* heap = rng->heap;
  749. wc_FreeRng(rng);
  750. ForceZero(rng, sizeof(WC_RNG));
  751. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  752. (void)heap;
  753. }
  754. }
  755. int wc_InitRng(WC_RNG* rng)
  756. {
  757. return _InitRng(rng, NULL, 0, NULL, INVALID_DEVID);
  758. }
  759. int wc_InitRng_ex(WC_RNG* rng, void* heap, int devId)
  760. {
  761. return _InitRng(rng, NULL, 0, heap, devId);
  762. }
  763. int wc_InitRngNonce(WC_RNG* rng, byte* nonce, word32 nonceSz)
  764. {
  765. return _InitRng(rng, nonce, nonceSz, NULL, INVALID_DEVID);
  766. }
  767. int wc_InitRngNonce_ex(WC_RNG* rng, byte* nonce, word32 nonceSz,
  768. void* heap, int devId)
  769. {
  770. return _InitRng(rng, nonce, nonceSz, heap, devId);
  771. }
  772. /* place a generated block in output */
  773. WOLFSSL_ABI
  774. int wc_RNG_GenerateBlock(WC_RNG* rng, byte* output, word32 sz)
  775. {
  776. int ret;
  777. if (rng == NULL || output == NULL)
  778. return BAD_FUNC_ARG;
  779. if (sz == 0)
  780. return 0;
  781. #ifdef WOLF_CRYPTO_CB
  782. if (rng->devId != INVALID_DEVID) {
  783. ret = wc_CryptoCb_RandomBlock(rng, output, sz);
  784. if (ret != CRYPTOCB_UNAVAILABLE)
  785. return ret;
  786. /* fall-through when unavailable */
  787. }
  788. #endif
  789. #ifdef HAVE_INTEL_RDRAND
  790. if (IS_INTEL_RDRAND(intel_flags))
  791. return wc_GenerateRand_IntelRD(NULL, output, sz);
  792. #endif
  793. #if defined(WOLFSSL_SILABS_SE_ACCEL) && defined(WOLFSSL_SILABS_TRNG)
  794. return silabs_GenerateRand(output, sz);
  795. #endif
  796. #if defined(WOLFSSL_ASYNC_CRYPT)
  797. if (rng->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RNG) {
  798. /* these are blocking */
  799. #ifdef HAVE_CAVIUM
  800. return NitroxRngGenerateBlock(rng, output, sz);
  801. #elif defined(HAVE_INTEL_QA) && defined(QAT_ENABLE_RNG)
  802. return IntelQaDrbg(&rng->asyncDev, output, sz);
  803. #else
  804. /* simulator not supported */
  805. #endif
  806. }
  807. #endif
  808. #ifdef CUSTOM_RAND_GENERATE_BLOCK
  809. XMEMSET(output, 0, sz);
  810. ret = CUSTOM_RAND_GENERATE_BLOCK(output, sz);
  811. #else
  812. #ifdef HAVE_HASHDRBG
  813. if (sz > RNG_MAX_BLOCK_LEN)
  814. return BAD_FUNC_ARG;
  815. if (rng->status != DRBG_OK)
  816. return RNG_FAILURE_E;
  817. ret = Hash_DRBG_Generate((DRBG_internal *)rng->drbg, output, sz);
  818. if (ret == DRBG_NEED_RESEED) {
  819. if (wc_RNG_HealthTestLocal(1) == 0) {
  820. byte newSeed[SEED_SZ + SEED_BLOCK_SZ];
  821. ret = wc_GenerateSeed(&rng->seed, newSeed,
  822. SEED_SZ + SEED_BLOCK_SZ);
  823. if (ret != 0)
  824. ret = DRBG_FAILURE;
  825. else
  826. ret = wc_RNG_TestSeed(newSeed, SEED_SZ + SEED_BLOCK_SZ);
  827. if (ret == DRBG_SUCCESS)
  828. ret = Hash_DRBG_Reseed((DRBG_internal *)rng->drbg, newSeed + SEED_BLOCK_SZ,
  829. SEED_SZ);
  830. if (ret == DRBG_SUCCESS)
  831. ret = Hash_DRBG_Generate((DRBG_internal *)rng->drbg, output, sz);
  832. ForceZero(newSeed, sizeof(newSeed));
  833. }
  834. else
  835. ret = DRBG_CONT_FAILURE;
  836. }
  837. if (ret == DRBG_SUCCESS) {
  838. ret = 0;
  839. }
  840. else if (ret == DRBG_CONT_FAILURE) {
  841. ret = DRBG_CONT_FIPS_E;
  842. rng->status = DRBG_CONT_FAILED;
  843. }
  844. else {
  845. ret = RNG_FAILURE_E;
  846. rng->status = DRBG_FAILED;
  847. }
  848. #else
  849. /* if we get here then there is an RNG configuration error */
  850. ret = RNG_FAILURE_E;
  851. #endif /* HAVE_HASHDRBG */
  852. #endif /* CUSTOM_RAND_GENERATE_BLOCK */
  853. return ret;
  854. }
  855. int wc_RNG_GenerateByte(WC_RNG* rng, byte* b)
  856. {
  857. return wc_RNG_GenerateBlock(rng, b, 1);
  858. }
  859. int wc_FreeRng(WC_RNG* rng)
  860. {
  861. int ret = 0;
  862. if (rng == NULL)
  863. return BAD_FUNC_ARG;
  864. #if defined(WOLFSSL_ASYNC_CRYPT)
  865. wolfAsync_DevCtxFree(&rng->asyncDev, WOLFSSL_ASYNC_MARKER_RNG);
  866. #endif
  867. #ifdef HAVE_HASHDRBG
  868. if (rng->drbg != NULL) {
  869. if (Hash_DRBG_Uninstantiate((DRBG_internal *)rng->drbg) != DRBG_SUCCESS)
  870. ret = RNG_FAILURE_E;
  871. #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
  872. XFREE(rng->drbg, rng->heap, DYNAMIC_TYPE_RNG);
  873. #endif
  874. rng->drbg = NULL;
  875. }
  876. rng->status = DRBG_NOT_INIT;
  877. #endif /* HAVE_HASHDRBG */
  878. return ret;
  879. }
  880. #ifdef HAVE_HASHDRBG
  881. int wc_RNG_HealthTest(int reseed, const byte* seedA, word32 seedASz,
  882. const byte* seedB, word32 seedBSz,
  883. byte* output, word32 outputSz)
  884. {
  885. return wc_RNG_HealthTest_ex(reseed, NULL, 0,
  886. seedA, seedASz, seedB, seedBSz,
  887. output, outputSz,
  888. NULL, INVALID_DEVID);
  889. }
  890. int wc_RNG_HealthTest_ex(int reseed, const byte* nonce, word32 nonceSz,
  891. const byte* seedA, word32 seedASz,
  892. const byte* seedB, word32 seedBSz,
  893. byte* output, word32 outputSz,
  894. void* heap, int devId)
  895. {
  896. int ret = -1;
  897. DRBG_internal* drbg;
  898. #ifndef WOLFSSL_SMALL_STACK
  899. DRBG_internal drbg_var;
  900. #endif
  901. if (seedA == NULL || output == NULL) {
  902. return BAD_FUNC_ARG;
  903. }
  904. if (reseed != 0 && seedB == NULL) {
  905. return BAD_FUNC_ARG;
  906. }
  907. if (outputSz != RNG_HEALTH_TEST_CHECK_SIZE) {
  908. return ret;
  909. }
  910. #ifdef WOLFSSL_SMALL_STACK
  911. drbg = (DRBG_internal*)XMALLOC(sizeof(DRBG_internal), NULL, DYNAMIC_TYPE_RNG);
  912. if (drbg == NULL) {
  913. return MEMORY_E;
  914. }
  915. #else
  916. drbg = &drbg_var;
  917. #endif
  918. if (Hash_DRBG_Instantiate(drbg, seedA, seedASz, nonce, nonceSz,
  919. heap, devId) != 0) {
  920. goto exit_rng_ht;
  921. }
  922. if (reseed) {
  923. if (Hash_DRBG_Reseed(drbg, seedB, seedBSz) != 0) {
  924. goto exit_rng_ht;
  925. }
  926. }
  927. /* This call to generate is prescribed by the NIST DRBGVS
  928. * procedure. The results are thrown away. The known
  929. * answer test checks the second block of DRBG out of
  930. * the generator to ensure the internal state is updated
  931. * as expected. */
  932. if (Hash_DRBG_Generate(drbg, output, outputSz) != 0) {
  933. goto exit_rng_ht;
  934. }
  935. if (Hash_DRBG_Generate(drbg, output, outputSz) != 0) {
  936. goto exit_rng_ht;
  937. }
  938. /* Mark success */
  939. ret = 0;
  940. exit_rng_ht:
  941. /* This is safe to call even if Hash_DRBG_Instantiate fails */
  942. if (Hash_DRBG_Uninstantiate(drbg) != 0) {
  943. ret = -1;
  944. }
  945. #ifdef WOLFSSL_SMALL_STACK
  946. XFREE(drbg, NULL, DYNAMIC_TYPE_RNG);
  947. #endif
  948. return ret;
  949. }
  950. const FLASH_QUALIFIER byte seedA_data[] = {
  951. 0x63, 0x36, 0x33, 0x77, 0xe4, 0x1e, 0x86, 0x46, 0x8d, 0xeb, 0x0a, 0xb4,
  952. 0xa8, 0xed, 0x68, 0x3f, 0x6a, 0x13, 0x4e, 0x47, 0xe0, 0x14, 0xc7, 0x00,
  953. 0x45, 0x4e, 0x81, 0xe9, 0x53, 0x58, 0xa5, 0x69, 0x80, 0x8a, 0xa3, 0x8f,
  954. 0x2a, 0x72, 0xa6, 0x23, 0x59, 0x91, 0x5a, 0x9f, 0x8a, 0x04, 0xca, 0x68
  955. };
  956. const FLASH_QUALIFIER byte reseedSeedA_data[] = {
  957. 0xe6, 0x2b, 0x8a, 0x8e, 0xe8, 0xf1, 0x41, 0xb6, 0x98, 0x05, 0x66, 0xe3,
  958. 0xbf, 0xe3, 0xc0, 0x49, 0x03, 0xda, 0xd4, 0xac, 0x2c, 0xdf, 0x9f, 0x22,
  959. 0x80, 0x01, 0x0a, 0x67, 0x39, 0xbc, 0x83, 0xd3
  960. };
  961. const FLASH_QUALIFIER byte outputA_data[] = {
  962. 0x04, 0xee, 0xc6, 0x3b, 0xb2, 0x31, 0xdf, 0x2c, 0x63, 0x0a, 0x1a, 0xfb,
  963. 0xe7, 0x24, 0x94, 0x9d, 0x00, 0x5a, 0x58, 0x78, 0x51, 0xe1, 0xaa, 0x79,
  964. 0x5e, 0x47, 0x73, 0x47, 0xc8, 0xb0, 0x56, 0x62, 0x1c, 0x18, 0xbd, 0xdc,
  965. 0xdd, 0x8d, 0x99, 0xfc, 0x5f, 0xc2, 0xb9, 0x20, 0x53, 0xd8, 0xcf, 0xac,
  966. 0xfb, 0x0b, 0xb8, 0x83, 0x12, 0x05, 0xfa, 0xd1, 0xdd, 0xd6, 0xc0, 0x71,
  967. 0x31, 0x8a, 0x60, 0x18, 0xf0, 0x3b, 0x73, 0xf5, 0xed, 0xe4, 0xd4, 0xd0,
  968. 0x71, 0xf9, 0xde, 0x03, 0xfd, 0x7a, 0xea, 0x10, 0x5d, 0x92, 0x99, 0xb8,
  969. 0xaf, 0x99, 0xaa, 0x07, 0x5b, 0xdb, 0x4d, 0xb9, 0xaa, 0x28, 0xc1, 0x8d,
  970. 0x17, 0x4b, 0x56, 0xee, 0x2a, 0x01, 0x4d, 0x09, 0x88, 0x96, 0xff, 0x22,
  971. 0x82, 0xc9, 0x55, 0xa8, 0x19, 0x69, 0xe0, 0x69, 0xfa, 0x8c, 0xe0, 0x07,
  972. 0xa1, 0x80, 0x18, 0x3a, 0x07, 0xdf, 0xae, 0x17
  973. };
  974. const FLASH_QUALIFIER byte seedB_data[] = {
  975. 0xa6, 0x5a, 0xd0, 0xf3, 0x45, 0xdb, 0x4e, 0x0e, 0xff, 0xe8, 0x75, 0xc3,
  976. 0xa2, 0xe7, 0x1f, 0x42, 0xc7, 0x12, 0x9d, 0x62, 0x0f, 0xf5, 0xc1, 0x19,
  977. 0xa9, 0xef, 0x55, 0xf0, 0x51, 0x85, 0xe0, 0xfb, /* nonce next */
  978. 0x85, 0x81, 0xf9, 0x31, 0x75, 0x17, 0x27, 0x6e, 0x06, 0xe9, 0x60, 0x7d,
  979. 0xdb, 0xcb, 0xcc, 0x2e
  980. };
  981. const FLASH_QUALIFIER byte outputB_data[] = {
  982. 0xd3, 0xe1, 0x60, 0xc3, 0x5b, 0x99, 0xf3, 0x40, 0xb2, 0x62, 0x82, 0x64,
  983. 0xd1, 0x75, 0x10, 0x60, 0xe0, 0x04, 0x5d, 0xa3, 0x83, 0xff, 0x57, 0xa5,
  984. 0x7d, 0x73, 0xa6, 0x73, 0xd2, 0xb8, 0xd8, 0x0d, 0xaa, 0xf6, 0xa6, 0xc3,
  985. 0x5a, 0x91, 0xbb, 0x45, 0x79, 0xd7, 0x3f, 0xd0, 0xc8, 0xfe, 0xd1, 0x11,
  986. 0xb0, 0x39, 0x13, 0x06, 0x82, 0x8a, 0xdf, 0xed, 0x52, 0x8f, 0x01, 0x81,
  987. 0x21, 0xb3, 0xfe, 0xbd, 0xc3, 0x43, 0xe7, 0x97, 0xb8, 0x7d, 0xbb, 0x63,
  988. 0xdb, 0x13, 0x33, 0xde, 0xd9, 0xd1, 0xec, 0xe1, 0x77, 0xcf, 0xa6, 0xb7,
  989. 0x1f, 0xe8, 0xab, 0x1d, 0xa4, 0x66, 0x24, 0xed, 0x64, 0x15, 0xe5, 0x1c,
  990. 0xcd, 0xe2, 0xc7, 0xca, 0x86, 0xe2, 0x83, 0x99, 0x0e, 0xea, 0xeb, 0x91,
  991. 0x12, 0x04, 0x15, 0x52, 0x8b, 0x22, 0x95, 0x91, 0x02, 0x81, 0xb0, 0x2d,
  992. 0xd4, 0x31, 0xf4, 0xc9, 0xf7, 0x04, 0x27, 0xdf
  993. };
  994. static int wc_RNG_HealthTestLocal(int reseed)
  995. {
  996. int ret = 0;
  997. #ifdef WOLFSSL_SMALL_STACK
  998. byte* check;
  999. #else
  1000. byte check[RNG_HEALTH_TEST_CHECK_SIZE];
  1001. #endif
  1002. #ifdef WOLFSSL_SMALL_STACK
  1003. check = (byte*)XMALLOC(RNG_HEALTH_TEST_CHECK_SIZE, NULL,
  1004. DYNAMIC_TYPE_TMP_BUFFER);
  1005. if (check == NULL) {
  1006. return MEMORY_E;
  1007. }
  1008. #endif
  1009. if (reseed) {
  1010. #ifdef WOLFSSL_USE_FLASHMEM
  1011. byte* seedA = (byte*)XMALLOC(sizeof(seedA_data), NULL,
  1012. DYNAMIC_TYPE_TMP_BUFFER);
  1013. byte* reseedSeedA = (byte*)XMALLOC(sizeof(reseedSeedA_data), NULL,
  1014. DYNAMIC_TYPE_TMP_BUFFER);
  1015. byte* outputA = (byte*)XMALLOC(sizeof(outputA_data), NULL,
  1016. DYNAMIC_TYPE_TMP_BUFFER);
  1017. if (!seedA || !reseedSeedA || !outputA) {
  1018. XFREE(seedA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1019. XFREE(reseedSeedA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1020. XFREE(outputA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1021. ret = MEMORY_E;
  1022. }
  1023. else {
  1024. XMEMCPY_P(seedA, seedA_data, sizeof(seedA_data));
  1025. XMEMCPY_P(reseedSeedA, reseedSeedA_data, sizeof(reseedSeedA_data));
  1026. XMEMCPY_P(outputA, outputA_data, sizeof(outputA_data));
  1027. #else
  1028. const byte* seedA = seedA_data;
  1029. const byte* reseedSeedA = reseedSeedA_data;
  1030. const byte* outputA = outputA_data;
  1031. #endif
  1032. ret = wc_RNG_HealthTest(1, seedA, sizeof(seedA_data),
  1033. reseedSeedA, sizeof(reseedSeedA_data),
  1034. check, RNG_HEALTH_TEST_CHECK_SIZE);
  1035. if (ret == 0) {
  1036. if (ConstantCompare(check, outputA,
  1037. RNG_HEALTH_TEST_CHECK_SIZE) != 0)
  1038. ret = -1;
  1039. }
  1040. #ifdef WOLFSSL_USE_FLASHMEM
  1041. XFREE(seedA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1042. XFREE(reseedSeedA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1043. XFREE(outputA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1044. }
  1045. #endif
  1046. }
  1047. else {
  1048. #ifdef WOLFSSL_USE_FLASHMEM
  1049. byte* seedB = (byte*)XMALLOC(sizeof(seedB_data), NULL,
  1050. DYNAMIC_TYPE_TMP_BUFFER);
  1051. byte* outputB = (byte*)XMALLOC(sizeof(outputB_data), NULL,
  1052. DYNAMIC_TYPE_TMP_BUFFER);
  1053. if (!seedB || !outputB) {
  1054. XFREE(seedB, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1055. XFREE(outputB, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1056. ret = MEMORY_E;
  1057. }
  1058. else {
  1059. XMEMCPY_P(seedB, seedB_data, sizeof(seedB_data));
  1060. XMEMCPY_P(outputB, outputB_data, sizeof(outputB_data));
  1061. #else
  1062. const byte* seedB = seedB_data;
  1063. const byte* outputB = outputB_data;
  1064. #endif
  1065. ret = wc_RNG_HealthTest(0, seedB, sizeof(seedB_data),
  1066. NULL, 0,
  1067. check, RNG_HEALTH_TEST_CHECK_SIZE);
  1068. if (ret == 0) {
  1069. if (ConstantCompare(check, outputB,
  1070. RNG_HEALTH_TEST_CHECK_SIZE) != 0)
  1071. ret = -1;
  1072. }
  1073. /* The previous test cases use a large seed instead of a seed and nonce.
  1074. * seedB is actually from a test case with a seed and nonce, and
  1075. * just concatenates them. The pivot point between seed and nonce is
  1076. * byte 32, feed them into the health test separately. */
  1077. if (ret == 0) {
  1078. ret = wc_RNG_HealthTest_ex(0,
  1079. seedB + 32, sizeof(seedB_data) - 32,
  1080. seedB, 32,
  1081. NULL, 0,
  1082. check, RNG_HEALTH_TEST_CHECK_SIZE,
  1083. NULL, INVALID_DEVID);
  1084. if (ret == 0) {
  1085. if (ConstantCompare(check, outputB, sizeof(outputB_data)) != 0)
  1086. ret = -1;
  1087. }
  1088. }
  1089. #ifdef WOLFSSL_USE_FLASHMEM
  1090. XFREE(seedB, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1091. XFREE(outputB, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1092. }
  1093. #endif
  1094. }
  1095. #ifdef WOLFSSL_SMALL_STACK
  1096. XFREE(check, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1097. #endif
  1098. return ret;
  1099. }
  1100. #endif /* HAVE_HASHDRBG */
  1101. #ifdef HAVE_WNR
  1102. /*
  1103. * Init global Whitewood netRandom context
  1104. * Returns 0 on success, negative on error
  1105. */
  1106. int wc_InitNetRandom(const char* configFile, wnr_hmac_key hmac_cb, int timeout)
  1107. {
  1108. if (configFile == NULL || timeout < 0)
  1109. return BAD_FUNC_ARG;
  1110. if (wnr_mutex_init > 0) {
  1111. WOLFSSL_MSG("netRandom context already created, skipping");
  1112. return 0;
  1113. }
  1114. if (wc_InitMutex(&wnr_mutex) != 0) {
  1115. WOLFSSL_MSG("Bad Init Mutex wnr_mutex");
  1116. return BAD_MUTEX_E;
  1117. }
  1118. wnr_mutex_init = 1;
  1119. if (wc_LockMutex(&wnr_mutex) != 0) {
  1120. WOLFSSL_MSG("Bad Lock Mutex wnr_mutex");
  1121. return BAD_MUTEX_E;
  1122. }
  1123. /* store entropy timeout */
  1124. wnr_timeout = timeout;
  1125. /* create global wnr_context struct */
  1126. if (wnr_create(&wnr_ctx) != WNR_ERROR_NONE) {
  1127. WOLFSSL_MSG("Error creating global netRandom context");
  1128. return RNG_FAILURE_E;
  1129. }
  1130. /* load config file */
  1131. if (wnr_config_loadf(wnr_ctx, (char*)configFile) != WNR_ERROR_NONE) {
  1132. WOLFSSL_MSG("Error loading config file into netRandom context");
  1133. wnr_destroy(wnr_ctx);
  1134. wnr_ctx = NULL;
  1135. return RNG_FAILURE_E;
  1136. }
  1137. /* create/init polling mechanism */
  1138. if (wnr_poll_create() != WNR_ERROR_NONE) {
  1139. printf("ERROR: wnr_poll_create() failed\n");
  1140. WOLFSSL_MSG("Error initializing netRandom polling mechanism");
  1141. wnr_destroy(wnr_ctx);
  1142. wnr_ctx = NULL;
  1143. return RNG_FAILURE_E;
  1144. }
  1145. /* validate config, set HMAC callback (optional) */
  1146. if (wnr_setup(wnr_ctx, hmac_cb) != WNR_ERROR_NONE) {
  1147. WOLFSSL_MSG("Error setting up netRandom context");
  1148. wnr_destroy(wnr_ctx);
  1149. wnr_ctx = NULL;
  1150. wnr_poll_destroy();
  1151. return RNG_FAILURE_E;
  1152. }
  1153. wc_UnLockMutex(&wnr_mutex);
  1154. return 0;
  1155. }
  1156. /*
  1157. * Free global Whitewood netRandom context
  1158. * Returns 0 on success, negative on error
  1159. */
  1160. int wc_FreeNetRandom(void)
  1161. {
  1162. if (wnr_mutex_init > 0) {
  1163. if (wc_LockMutex(&wnr_mutex) != 0) {
  1164. WOLFSSL_MSG("Bad Lock Mutex wnr_mutex");
  1165. return BAD_MUTEX_E;
  1166. }
  1167. if (wnr_ctx != NULL) {
  1168. wnr_destroy(wnr_ctx);
  1169. wnr_ctx = NULL;
  1170. }
  1171. wnr_poll_destroy();
  1172. wc_UnLockMutex(&wnr_mutex);
  1173. wc_FreeMutex(&wnr_mutex);
  1174. wnr_mutex_init = 0;
  1175. }
  1176. return 0;
  1177. }
  1178. #endif /* HAVE_WNR */
  1179. #if defined(HAVE_INTEL_RDRAND) || defined(HAVE_INTEL_RDSEED)
  1180. #ifdef WOLFSSL_ASYNC_CRYPT
  1181. /* need more retries if multiple cores */
  1182. #define INTELRD_RETRY (32 * 8)
  1183. #else
  1184. #define INTELRD_RETRY 32
  1185. #endif
  1186. #ifdef HAVE_INTEL_RDSEED
  1187. #ifndef USE_INTEL_INTRINSICS
  1188. /* return 0 on success */
  1189. static WC_INLINE int IntelRDseed64(word64* seed)
  1190. {
  1191. unsigned char ok;
  1192. __asm__ volatile("rdseed %0; setc %1":"=r"(*seed), "=qm"(ok));
  1193. return (ok) ? 0 : -1;
  1194. }
  1195. #else /* USE_INTEL_INTRINSICS */
  1196. /* The compiler Visual Studio uses does not allow inline assembly.
  1197. * It does allow for Intel intrinsic functions. */
  1198. /* return 0 on success */
  1199. # ifdef __GNUC__
  1200. __attribute__((target("rdseed")))
  1201. # endif
  1202. static WC_INLINE int IntelRDseed64(word64* seed)
  1203. {
  1204. int ok;
  1205. ok = _rdseed64_step((unsigned long long*) seed);
  1206. return (ok) ? 0 : -1;
  1207. }
  1208. #endif /* USE_INTEL_INTRINSICS */
  1209. /* return 0 on success */
  1210. static WC_INLINE int IntelRDseed64_r(word64* rnd)
  1211. {
  1212. int i;
  1213. for (i = 0; i < INTELRD_RETRY; i++) {
  1214. if (IntelRDseed64(rnd) == 0)
  1215. return 0;
  1216. }
  1217. return -1;
  1218. }
  1219. #ifndef WOLFSSL_LINUXKM
  1220. /* return 0 on success */
  1221. static int wc_GenerateSeed_IntelRD(OS_Seed* os, byte* output, word32 sz)
  1222. {
  1223. int ret;
  1224. word64 rndTmp;
  1225. (void)os;
  1226. if (!IS_INTEL_RDSEED(intel_flags))
  1227. return -1;
  1228. for (; (sz / sizeof(word64)) > 0; sz -= sizeof(word64),
  1229. output += sizeof(word64)) {
  1230. ret = IntelRDseed64_r((word64*)output);
  1231. if (ret != 0)
  1232. return ret;
  1233. }
  1234. if (sz == 0)
  1235. return 0;
  1236. /* handle unaligned remainder */
  1237. ret = IntelRDseed64_r(&rndTmp);
  1238. if (ret != 0)
  1239. return ret;
  1240. XMEMCPY(output, &rndTmp, sz);
  1241. ForceZero(&rndTmp, sizeof(rndTmp));
  1242. return 0;
  1243. }
  1244. #endif
  1245. #endif /* HAVE_INTEL_RDSEED */
  1246. #ifdef HAVE_INTEL_RDRAND
  1247. #ifndef USE_INTEL_INTRINSICS
  1248. /* return 0 on success */
  1249. static WC_INLINE int IntelRDrand64(word64 *rnd)
  1250. {
  1251. unsigned char ok;
  1252. __asm__ volatile("rdrand %0; setc %1":"=r"(*rnd), "=qm"(ok));
  1253. return (ok) ? 0 : -1;
  1254. }
  1255. #else /* USE_INTEL_INTRINSICS */
  1256. /* The compiler Visual Studio uses does not allow inline assembly.
  1257. * It does allow for Intel intrinsic functions. */
  1258. /* return 0 on success */
  1259. # ifdef __GNUC__
  1260. __attribute__((target("rdrnd")))
  1261. # endif
  1262. static WC_INLINE int IntelRDrand64(word64 *rnd)
  1263. {
  1264. int ok;
  1265. ok = _rdrand64_step((unsigned long long*) rnd);
  1266. return (ok) ? 0 : -1;
  1267. }
  1268. #endif /* USE_INTEL_INTRINSICS */
  1269. /* return 0 on success */
  1270. static WC_INLINE int IntelRDrand64_r(word64 *rnd)
  1271. {
  1272. int i;
  1273. for (i = 0; i < INTELRD_RETRY; i++) {
  1274. if (IntelRDrand64(rnd) == 0)
  1275. return 0;
  1276. }
  1277. return -1;
  1278. }
  1279. /* return 0 on success */
  1280. static int wc_GenerateRand_IntelRD(OS_Seed* os, byte* output, word32 sz)
  1281. {
  1282. int ret;
  1283. word64 rndTmp;
  1284. (void)os;
  1285. if (!IS_INTEL_RDRAND(intel_flags))
  1286. return -1;
  1287. for (; (sz / sizeof(word64)) > 0; sz -= sizeof(word64),
  1288. output += sizeof(word64)) {
  1289. ret = IntelRDrand64_r((word64 *)output);
  1290. if (ret != 0)
  1291. return ret;
  1292. }
  1293. if (sz == 0)
  1294. return 0;
  1295. /* handle unaligned remainder */
  1296. ret = IntelRDrand64_r(&rndTmp);
  1297. if (ret != 0)
  1298. return ret;
  1299. XMEMCPY(output, &rndTmp, sz);
  1300. return 0;
  1301. }
  1302. #endif /* HAVE_INTEL_RDRAND */
  1303. #endif /* HAVE_INTEL_RDRAND || HAVE_INTEL_RDSEED */
  1304. /* Begin wc_GenerateSeed Implementations */
  1305. #if defined(CUSTOM_RAND_GENERATE_SEED)
  1306. /* Implement your own random generation function
  1307. * Return 0 to indicate success
  1308. * int rand_gen_seed(byte* output, word32 sz);
  1309. * #define CUSTOM_RAND_GENERATE_SEED rand_gen_seed */
  1310. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1311. {
  1312. (void)os; /* Suppress unused arg warning */
  1313. return CUSTOM_RAND_GENERATE_SEED(output, sz);
  1314. }
  1315. #elif defined(CUSTOM_RAND_GENERATE_SEED_OS)
  1316. /* Implement your own random generation function,
  1317. * which includes OS_Seed.
  1318. * Return 0 to indicate success
  1319. * int rand_gen_seed(OS_Seed* os, byte* output, word32 sz);
  1320. * #define CUSTOM_RAND_GENERATE_SEED_OS rand_gen_seed */
  1321. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1322. {
  1323. return CUSTOM_RAND_GENERATE_SEED_OS(os, output, sz);
  1324. }
  1325. #elif defined(CUSTOM_RAND_GENERATE)
  1326. /* Implement your own random generation function
  1327. * word32 rand_gen(void);
  1328. * #define CUSTOM_RAND_GENERATE rand_gen */
  1329. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1330. {
  1331. word32 i = 0;
  1332. (void)os;
  1333. while (i < sz)
  1334. {
  1335. /* If not aligned or there is odd/remainder */
  1336. if( (i + sizeof(CUSTOM_RAND_TYPE)) > sz ||
  1337. ((wolfssl_word)&output[i] % sizeof(CUSTOM_RAND_TYPE)) != 0
  1338. ) {
  1339. /* Single byte at a time */
  1340. output[i++] = (byte)CUSTOM_RAND_GENERATE();
  1341. }
  1342. else {
  1343. /* Use native 8, 16, 32 or 64 copy instruction */
  1344. *((CUSTOM_RAND_TYPE*)&output[i]) = CUSTOM_RAND_GENERATE();
  1345. i += sizeof(CUSTOM_RAND_TYPE);
  1346. }
  1347. }
  1348. return 0;
  1349. }
  1350. #elif defined(WOLFSSL_SGX)
  1351. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1352. {
  1353. int ret = !SGX_SUCCESS;
  1354. int i, read_max = 10;
  1355. for (i = 0; i < read_max && ret != SGX_SUCCESS; i++) {
  1356. ret = sgx_read_rand(output, sz);
  1357. }
  1358. (void)os;
  1359. return (ret == SGX_SUCCESS) ? 0 : 1;
  1360. }
  1361. #elif defined(USE_WINDOWS_API)
  1362. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1363. {
  1364. #ifdef WOLF_CRYPTO_CB
  1365. int ret;
  1366. if (os != NULL && os->devId != INVALID_DEVID) {
  1367. ret = wc_CryptoCb_RandomSeed(os, output, sz);
  1368. if (ret != CRYPTOCB_UNAVAILABLE)
  1369. return ret;
  1370. /* fall-through when unavailable */
  1371. }
  1372. #endif
  1373. #ifdef HAVE_INTEL_RDSEED
  1374. if (IS_INTEL_RDSEED(intel_flags)) {
  1375. if (!wc_GenerateSeed_IntelRD(NULL, output, sz)) {
  1376. /* success, we're done */
  1377. return 0;
  1378. }
  1379. #ifdef FORCE_FAILURE_RDSEED
  1380. /* don't fall back to CryptoAPI */
  1381. return READ_RAN_E;
  1382. #endif
  1383. }
  1384. #endif /* HAVE_INTEL_RDSEED */
  1385. if(!CryptAcquireContext(&os->handle, 0, 0, PROV_RSA_FULL,
  1386. CRYPT_VERIFYCONTEXT))
  1387. return WINCRYPT_E;
  1388. if (!CryptGenRandom(os->handle, sz, output))
  1389. return CRYPTGEN_E;
  1390. CryptReleaseContext(os->handle, 0);
  1391. return 0;
  1392. }
  1393. #elif defined(HAVE_RTP_SYS) || defined(EBSNET)
  1394. #include "rtprand.h" /* rtp_rand () */
  1395. #include "rtptime.h" /* rtp_get_system_msec() */
  1396. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1397. {
  1398. word32 i;
  1399. rtp_srand(rtp_get_system_msec());
  1400. for (i = 0; i < sz; i++ ) {
  1401. output[i] = rtp_rand() % 256;
  1402. }
  1403. return 0;
  1404. }
  1405. #elif (defined(WOLFSSL_ATMEL) || defined(WOLFSSL_ATECC_RNG)) && \
  1406. !defined(WOLFSSL_PIC32MZ_RNG)
  1407. /* enable ATECC RNG unless using PIC32MZ one instead */
  1408. #include <wolfssl/wolfcrypt/port/atmel/atmel.h>
  1409. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1410. {
  1411. int ret = 0;
  1412. (void)os;
  1413. if (output == NULL) {
  1414. return BUFFER_E;
  1415. }
  1416. ret = atmel_get_random_number(sz, output);
  1417. return ret;
  1418. }
  1419. #elif defined(MICROCHIP_PIC32)
  1420. #ifdef MICROCHIP_MPLAB_HARMONY
  1421. #ifdef MICROCHIP_MPLAB_HARMONY_3
  1422. #include "system/time/sys_time.h"
  1423. #define PIC32_SEED_COUNT SYS_TIME_CounterGet
  1424. #else
  1425. #define PIC32_SEED_COUNT _CP0_GET_COUNT
  1426. #endif
  1427. #else
  1428. #if !defined(WOLFSSL_MICROCHIP_PIC32MZ)
  1429. #include <peripheral/timer.h>
  1430. #endif
  1431. extern word32 ReadCoreTimer(void);
  1432. #define PIC32_SEED_COUNT ReadCoreTimer
  1433. #endif
  1434. #ifdef WOLFSSL_PIC32MZ_RNG
  1435. #include "xc.h"
  1436. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1437. {
  1438. int i;
  1439. byte rnd[8];
  1440. word32 *rnd32 = (word32 *)rnd;
  1441. word32 size = sz;
  1442. byte* op = output;
  1443. #if ((__PIC32_FEATURE_SET0 == 'E') && (__PIC32_FEATURE_SET1 == 'C'))
  1444. RNGNUMGEN1 = _CP0_GET_COUNT();
  1445. RNGPOLY1 = _CP0_GET_COUNT();
  1446. RNGPOLY2 = _CP0_GET_COUNT();
  1447. RNGNUMGEN2 = _CP0_GET_COUNT();
  1448. #else
  1449. // All others can be seeded from the TRNG
  1450. RNGCONbits.TRNGMODE = 1;
  1451. RNGCONbits.TRNGEN = 1;
  1452. while (RNGCNT < 64);
  1453. RNGCONbits.LOAD = 1;
  1454. while (RNGCONbits.LOAD == 1);
  1455. while (RNGCNT < 64);
  1456. RNGPOLY2 = RNGSEED2;
  1457. RNGPOLY1 = RNGSEED1;
  1458. #endif
  1459. RNGCONbits.PLEN = 0x40;
  1460. RNGCONbits.PRNGEN = 1;
  1461. for (i=0; i<5; i++) { /* wait for RNGNUMGEN ready */
  1462. volatile int x, y;
  1463. x = RNGNUMGEN1;
  1464. y = RNGNUMGEN2;
  1465. (void)x;
  1466. (void)y;
  1467. }
  1468. do {
  1469. rnd32[0] = RNGNUMGEN1;
  1470. rnd32[1] = RNGNUMGEN2;
  1471. for(i=0; i<8; i++, op++) {
  1472. *op = rnd[i];
  1473. size --;
  1474. if(size==0)break;
  1475. }
  1476. } while(size);
  1477. return 0;
  1478. }
  1479. #else /* WOLFSSL_PIC32MZ_RNG */
  1480. /* uses the core timer, in nanoseconds to seed srand */
  1481. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1482. {
  1483. int i;
  1484. srand(PIC32_SEED_COUNT() * 25);
  1485. for (i = 0; i < sz; i++ ) {
  1486. output[i] = rand() % 256;
  1487. if ( (i % 8) == 7)
  1488. srand(PIC32_SEED_COUNT() * 25);
  1489. }
  1490. return 0;
  1491. }
  1492. #endif /* WOLFSSL_PIC32MZ_RNG */
  1493. #elif defined(FREESCALE_K70_RNGA) || defined(FREESCALE_RNGA)
  1494. /*
  1495. * wc_Generates a RNG seed using the Random Number Generator Accelerator
  1496. * on the Kinetis K70. Documentation located in Chapter 37 of
  1497. * K70 Sub-Family Reference Manual (see Note 3 in the README for link).
  1498. */
  1499. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1500. {
  1501. word32 i;
  1502. /* turn on RNGA module */
  1503. #if defined(SIM_SCGC3_RNGA_MASK)
  1504. SIM_SCGC3 |= SIM_SCGC3_RNGA_MASK;
  1505. #endif
  1506. #if defined(SIM_SCGC6_RNGA_MASK)
  1507. /* additionally needed for at least K64F */
  1508. SIM_SCGC6 |= SIM_SCGC6_RNGA_MASK;
  1509. #endif
  1510. /* set SLP bit to 0 - "RNGA is not in sleep mode" */
  1511. RNG_CR &= ~RNG_CR_SLP_MASK;
  1512. /* set HA bit to 1 - "security violations masked" */
  1513. RNG_CR |= RNG_CR_HA_MASK;
  1514. /* set GO bit to 1 - "output register loaded with data" */
  1515. RNG_CR |= RNG_CR_GO_MASK;
  1516. for (i = 0; i < sz; i++) {
  1517. /* wait for RNG FIFO to be full */
  1518. while((RNG_SR & RNG_SR_OREG_LVL(0xF)) == 0) {}
  1519. /* get value */
  1520. output[i] = RNG_OR;
  1521. }
  1522. return 0;
  1523. }
  1524. #elif defined(FREESCALE_K53_RNGB) || defined(FREESCALE_RNGB)
  1525. /*
  1526. * wc_Generates a RNG seed using the Random Number Generator (RNGB)
  1527. * on the Kinetis K53. Documentation located in Chapter 33 of
  1528. * K53 Sub-Family Reference Manual (see note in the README for link).
  1529. */
  1530. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1531. {
  1532. int i;
  1533. /* turn on RNGB module */
  1534. SIM_SCGC3 |= SIM_SCGC3_RNGB_MASK;
  1535. /* reset RNGB */
  1536. RNG_CMD |= RNG_CMD_SR_MASK;
  1537. /* FIFO generate interrupt, return all zeros on underflow,
  1538. * set auto reseed */
  1539. RNG_CR |= (RNG_CR_FUFMOD_MASK | RNG_CR_AR_MASK);
  1540. /* gen seed, clear interrupts, clear errors */
  1541. RNG_CMD |= (RNG_CMD_GS_MASK | RNG_CMD_CI_MASK | RNG_CMD_CE_MASK);
  1542. /* wait for seeding to complete */
  1543. while ((RNG_SR & RNG_SR_SDN_MASK) == 0) {}
  1544. for (i = 0; i < sz; i++) {
  1545. /* wait for a word to be available from FIFO */
  1546. while((RNG_SR & RNG_SR_FIFO_LVL_MASK) == 0) {}
  1547. /* get value */
  1548. output[i] = RNG_OUT;
  1549. }
  1550. return 0;
  1551. }
  1552. #elif defined(FREESCALE_KSDK_2_0_TRNG)
  1553. #ifndef TRNG0
  1554. #define TRNG0 TRNG
  1555. #endif
  1556. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1557. {
  1558. status_t status;
  1559. status = TRNG_GetRandomData(TRNG0, output, sz);
  1560. if (status == kStatus_Success)
  1561. {
  1562. return(0);
  1563. }
  1564. else
  1565. {
  1566. return RAN_BLOCK_E;
  1567. }
  1568. }
  1569. #elif defined(FREESCALE_KSDK_2_0_RNGA)
  1570. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1571. {
  1572. status_t status;
  1573. status = RNGA_GetRandomData(RNG, output, sz);
  1574. if (status == kStatus_Success)
  1575. {
  1576. return(0);
  1577. }
  1578. else
  1579. {
  1580. return RAN_BLOCK_E;
  1581. }
  1582. }
  1583. #elif defined(FREESCALE_RNGA)
  1584. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1585. {
  1586. RNGA_DRV_GetRandomData(RNGA_INSTANCE, output, sz);
  1587. return 0;
  1588. }
  1589. #elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) || \
  1590. defined(FREESCALE_KSDK_BM) || defined(FREESCALE_FREE_RTOS)
  1591. /*
  1592. * Fallback to USE_TEST_GENSEED if a FREESCALE platform did not match any
  1593. * of the TRNG/RNGA/RNGB support
  1594. */
  1595. #define USE_TEST_GENSEED
  1596. #elif defined(WOLFSSL_SILABS_SE_ACCEL)
  1597. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1598. {
  1599. (void)os;
  1600. return silabs_GenerateRand(output, sz);
  1601. }
  1602. #elif defined(STM32_RNG)
  1603. /* Generate a RNG seed using the hardware random number generator
  1604. * on the STM32F2/F4/F7/L4. */
  1605. #ifdef WOLFSSL_STM32_CUBEMX
  1606. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1607. {
  1608. int ret;
  1609. RNG_HandleTypeDef hrng;
  1610. word32 i = 0;
  1611. (void)os;
  1612. ret = wolfSSL_CryptHwMutexLock();
  1613. if (ret != 0) {
  1614. return ret;
  1615. }
  1616. /* enable RNG clock source */
  1617. __HAL_RCC_RNG_CLK_ENABLE();
  1618. /* enable RNG peripheral */
  1619. XMEMSET(&hrng, 0, sizeof(hrng));
  1620. hrng.Instance = RNG;
  1621. HAL_RNG_Init(&hrng);
  1622. while (i < sz) {
  1623. /* If not aligned or there is odd/remainder */
  1624. if( (i + sizeof(word32)) > sz ||
  1625. ((wolfssl_word)&output[i] % sizeof(word32)) != 0
  1626. ) {
  1627. /* Single byte at a time */
  1628. word32 tmpRng = 0;
  1629. if (HAL_RNG_GenerateRandomNumber(&hrng, &tmpRng) != HAL_OK) {
  1630. wolfSSL_CryptHwMutexUnLock();
  1631. return RAN_BLOCK_E;
  1632. }
  1633. output[i++] = (byte)tmpRng;
  1634. }
  1635. else {
  1636. /* Use native 32 instruction */
  1637. if (HAL_RNG_GenerateRandomNumber(&hrng, (word32*)&output[i]) != HAL_OK) {
  1638. wolfSSL_CryptHwMutexUnLock();
  1639. return RAN_BLOCK_E;
  1640. }
  1641. i += sizeof(word32);
  1642. }
  1643. }
  1644. wolfSSL_CryptHwMutexUnLock();
  1645. return 0;
  1646. }
  1647. #elif defined(WOLFSSL_STM32F427_RNG) || defined(WOLFSSL_STM32_RNG_NOLIB)
  1648. /* Generate a RNG seed using the hardware RNG on the STM32F427
  1649. * directly, following steps outlined in STM32F4 Reference
  1650. * Manual (Chapter 24) for STM32F4xx family. */
  1651. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1652. {
  1653. int ret;
  1654. word32 i;
  1655. (void)os;
  1656. ret = wolfSSL_CryptHwMutexLock();
  1657. if (ret != 0) {
  1658. return ret;
  1659. }
  1660. /* enable RNG peripheral clock */
  1661. RCC->AHB2ENR |= RCC_AHB2ENR_RNGEN;
  1662. /* enable RNG interrupt, set IE bit in RNG->CR register */
  1663. RNG->CR |= RNG_CR_IE;
  1664. /* enable RNG, set RNGEN bit in RNG->CR. Activates RNG,
  1665. * RNG_LFSR, and error detector */
  1666. RNG->CR |= RNG_CR_RNGEN;
  1667. /* verify no errors, make sure SEIS and CEIS bits are 0
  1668. * in RNG->SR register */
  1669. if (RNG->SR & (RNG_SR_SECS | RNG_SR_CECS)) {
  1670. wolfSSL_CryptHwMutexUnLock();
  1671. return RNG_FAILURE_E;
  1672. }
  1673. for (i = 0; i < sz; i++) {
  1674. /* wait until RNG number is ready */
  1675. while ((RNG->SR & RNG_SR_DRDY) == 0) { }
  1676. /* get value */
  1677. output[i] = RNG->DR;
  1678. }
  1679. wolfSSL_CryptHwMutexUnLock();
  1680. return 0;
  1681. }
  1682. #else
  1683. /* Generate a RNG seed using the STM32 Standard Peripheral Library */
  1684. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1685. {
  1686. int ret;
  1687. word32 i;
  1688. (void)os;
  1689. ret = wolfSSL_CryptHwMutexLock();
  1690. if (ret != 0) {
  1691. return ret;
  1692. }
  1693. /* enable RNG clock source */
  1694. RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_RNG, ENABLE);
  1695. /* reset RNG */
  1696. RNG_DeInit();
  1697. /* enable RNG peripheral */
  1698. RNG_Cmd(ENABLE);
  1699. /* verify no errors with RNG_CLK or Seed */
  1700. if (RNG_GetFlagStatus(RNG_FLAG_SECS | RNG_FLAG_CECS) != RESET) {
  1701. wolfSSL_CryptHwMutexUnLock();
  1702. return RNG_FAILURE_E;
  1703. }
  1704. for (i = 0; i < sz; i++) {
  1705. /* wait until RNG number is ready */
  1706. while (RNG_GetFlagStatus(RNG_FLAG_DRDY) == RESET) { }
  1707. /* get value */
  1708. output[i] = RNG_GetRandomNumber();
  1709. }
  1710. wolfSSL_CryptHwMutexUnLock();
  1711. return 0;
  1712. }
  1713. #endif /* WOLFSSL_STM32_CUBEMX */
  1714. #elif defined(WOLFSSL_TIRTOS)
  1715. #include <xdc/runtime/Timestamp.h>
  1716. #include <stdlib.h>
  1717. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1718. {
  1719. int i;
  1720. srand(xdc_runtime_Timestamp_get32());
  1721. for (i = 0; i < sz; i++ ) {
  1722. output[i] = rand() % 256;
  1723. if ((i % 8) == 7) {
  1724. srand(xdc_runtime_Timestamp_get32());
  1725. }
  1726. }
  1727. return 0;
  1728. }
  1729. #elif defined(WOLFSSL_PB)
  1730. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1731. {
  1732. word32 i;
  1733. for (i = 0; i < sz; i++)
  1734. output[i] = UTL_Rand();
  1735. (void)os;
  1736. return 0;
  1737. }
  1738. #elif defined(WOLFSSL_NUCLEUS)
  1739. #include "nucleus.h"
  1740. #include "kernel/plus_common.h"
  1741. #warning "potential for not enough entropy, currently being used for testing"
  1742. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1743. {
  1744. int i;
  1745. srand(NU_Get_Time_Stamp());
  1746. for (i = 0; i < sz; i++ ) {
  1747. output[i] = rand() % 256;
  1748. if ((i % 8) == 7) {
  1749. srand(NU_Get_Time_Stamp());
  1750. }
  1751. }
  1752. return 0;
  1753. }
  1754. #elif defined(WOLFSSL_DEOS) && !defined(CUSTOM_RAND_GENERATE)
  1755. #include "stdlib.h"
  1756. #warning "potential for not enough entropy, currently being used for testing Deos"
  1757. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1758. {
  1759. int i;
  1760. int seed = XTIME(0);
  1761. (void)os;
  1762. for (i = 0; i < sz; i++ ) {
  1763. output[i] = rand_r(&seed) % 256;
  1764. if ((i % 8) == 7) {
  1765. seed = XTIME(0);
  1766. rand_r(&seed);
  1767. }
  1768. }
  1769. return 0;
  1770. }
  1771. #elif defined(WOLFSSL_VXWORKS)
  1772. #include <randomNumGen.h>
  1773. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) {
  1774. STATUS status;
  1775. #ifdef VXWORKS_SIM
  1776. /* cannot generate true entropy with VxWorks simulator */
  1777. #warning "not enough entropy, simulator for testing only"
  1778. int i = 0;
  1779. for (i = 0; i < 1000; i++) {
  1780. randomAddTimeStamp();
  1781. }
  1782. #endif
  1783. status = randBytes (output, sz);
  1784. if (status == ERROR) {
  1785. return RNG_FAILURE_E;
  1786. }
  1787. return 0;
  1788. }
  1789. #elif defined(WOLFSSL_NRF51) || defined(WOLFSSL_NRF5x)
  1790. #include "app_error.h"
  1791. #include "nrf_drv_rng.h"
  1792. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1793. {
  1794. int remaining = sz, length, pos = 0;
  1795. word32 err_code;
  1796. byte available;
  1797. static byte initialized = 0;
  1798. (void)os;
  1799. /* Make sure RNG is running */
  1800. if (!initialized) {
  1801. err_code = nrf_drv_rng_init(NULL);
  1802. if (err_code != NRF_SUCCESS && err_code != NRF_ERROR_INVALID_STATE
  1803. #ifdef NRF_ERROR_MODULE_ALREADY_INITIALIZED
  1804. && err_code != NRF_ERROR_MODULE_ALREADY_INITIALIZED
  1805. #endif
  1806. ) {
  1807. return -1;
  1808. }
  1809. initialized = 1;
  1810. }
  1811. while (remaining > 0) {
  1812. available = 0;
  1813. nrf_drv_rng_bytes_available(&available); /* void func */
  1814. length = (remaining < available) ? remaining : available;
  1815. if (length > 0) {
  1816. err_code = nrf_drv_rng_rand(&output[pos], length);
  1817. if (err_code != NRF_SUCCESS) {
  1818. break;
  1819. }
  1820. remaining -= length;
  1821. pos += length;
  1822. }
  1823. }
  1824. return (err_code == NRF_SUCCESS) ? 0 : -1;
  1825. }
  1826. #elif defined(HAVE_WNR)
  1827. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1828. {
  1829. if (os == NULL || output == NULL || wnr_ctx == NULL ||
  1830. wnr_timeout < 0) {
  1831. return BAD_FUNC_ARG;
  1832. }
  1833. if (wnr_mutex_init == 0) {
  1834. WOLFSSL_MSG("netRandom context must be created before use");
  1835. return RNG_FAILURE_E;
  1836. }
  1837. if (wc_LockMutex(&wnr_mutex) != 0) {
  1838. WOLFSSL_MSG("Bad Lock Mutex wnr_mutex\n");
  1839. return BAD_MUTEX_E;
  1840. }
  1841. if (wnr_get_entropy(wnr_ctx, wnr_timeout, output, sz, sz) !=
  1842. WNR_ERROR_NONE)
  1843. return RNG_FAILURE_E;
  1844. wc_UnLockMutex(&wnr_mutex);
  1845. return 0;
  1846. }
  1847. #elif defined(INTIME_RTOS)
  1848. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1849. {
  1850. uint32_t randval;
  1851. word32 len;
  1852. if (output == NULL) {
  1853. return BUFFER_E;
  1854. }
  1855. #ifdef INTIMEVER
  1856. /* If INTIMEVER exists then it is INTIME RTOS v6 or later */
  1857. #define INTIME_RAND_FUNC arc4random
  1858. len = 4;
  1859. #else
  1860. /* v5 and older */
  1861. #define INTIME_RAND_FUNC rand
  1862. srand(time(0));
  1863. len = 2; /* don't use all 31 returned bits */
  1864. #endif
  1865. while (sz > 0) {
  1866. if (sz < len)
  1867. len = sz;
  1868. randval = INTIME_RAND_FUNC();
  1869. XMEMCPY(output, &randval, len);
  1870. output += len;
  1871. sz -= len;
  1872. }
  1873. (void)os;
  1874. return 0;
  1875. }
  1876. #elif defined(WOLFSSL_WICED)
  1877. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1878. {
  1879. int ret;
  1880. (void)os;
  1881. if (output == NULL || UINT16_MAX < sz) {
  1882. return BUFFER_E;
  1883. }
  1884. if ((ret = wiced_crypto_get_random((void*) output, sz) )
  1885. != WICED_SUCCESS) {
  1886. return ret;
  1887. }
  1888. return ret;
  1889. }
  1890. #elif defined(WOLFSSL_NETBURNER)
  1891. #warning using NetBurner pseudo random GetRandomByte for seed
  1892. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1893. {
  1894. word32 i;
  1895. (void)os;
  1896. if (output == NULL) {
  1897. return BUFFER_E;
  1898. }
  1899. for (i = 0; i < sz; i++) {
  1900. output[i] = GetRandomByte();
  1901. /* check if was a valid random number */
  1902. if (!RandomValid())
  1903. return RNG_FAILURE_E;
  1904. }
  1905. return 0;
  1906. }
  1907. #elif defined(IDIRECT_DEV_RANDOM)
  1908. extern int getRandom( int sz, unsigned char *output );
  1909. int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1910. {
  1911. int num_bytes_returned = 0;
  1912. num_bytes_returned = getRandom( (int) sz, (unsigned char *) output );
  1913. return 0;
  1914. }
  1915. #elif (defined(WOLFSSL_IMX6_CAAM) || defined(WOLFSSL_IMX6_CAAM_RNG))
  1916. #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h>
  1917. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1918. {
  1919. unsigned int args[4] = {0};
  1920. CAAM_BUFFER buf[1];
  1921. int ret = 0;
  1922. int times = 1000, i; /* 1000 is an arbitrary number chosen */
  1923. word32 idx = 0;
  1924. (void)os;
  1925. if (output == NULL) {
  1926. return BUFFER_E;
  1927. }
  1928. /* Check Waiting to make sure entropy is ready */
  1929. for (i = 0; i < times; i++) {
  1930. buf[0].BufferType = DataBuffer | LastBuffer;
  1931. buf[0].TheAddress = (CAAM_ADDRESS)(output + idx);
  1932. buf[0].Length = ((sz - idx) < WC_CAAM_MAX_ENTROPY)?
  1933. sz - idx : WC_CAAM_MAX_ENTROPY;
  1934. args[0] = buf[0].Length;
  1935. ret = wc_caamAddAndWait(buf, 1, args, CAAM_ENTROPY);
  1936. if (ret == 0) {
  1937. idx += buf[0].Length;
  1938. if (idx == sz)
  1939. break;
  1940. }
  1941. /* driver could be waiting for entropy */
  1942. if (ret != RAN_BLOCK_E && ret != 0) {
  1943. return ret;
  1944. }
  1945. usleep(100);
  1946. }
  1947. if (i == times && ret != 0) {
  1948. return RNG_FAILURE_E;
  1949. }
  1950. else { /* Success case */
  1951. ret = 0;
  1952. }
  1953. return ret;
  1954. }
  1955. #elif defined(WOLFSSL_APACHE_MYNEWT)
  1956. #include <stdlib.h>
  1957. #include "os/os_time.h"
  1958. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1959. {
  1960. int i;
  1961. srand(os_time_get());
  1962. for (i = 0; i < sz; i++ ) {
  1963. output[i] = rand() % 256;
  1964. if ((i % 8) == 7) {
  1965. srand(os_time_get());
  1966. }
  1967. }
  1968. return 0;
  1969. }
  1970. #elif defined(WOLFSSL_ESPIDF)
  1971. #if defined(WOLFSSL_ESPWROOM32) || defined(WOLFSSL_ESPWROOM32SE)
  1972. #include <esp_system.h>
  1973. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1974. {
  1975. word32 rand;
  1976. while (sz > 0) {
  1977. word32 len = sizeof(rand);
  1978. if (sz < len)
  1979. len = sz;
  1980. /* Get one random 32-bit word from hw RNG */
  1981. rand = esp_random( );
  1982. XMEMCPY(output, &rand, len);
  1983. output += len;
  1984. sz -= len;
  1985. }
  1986. return 0;
  1987. }
  1988. #endif /* end WOLFSSL_ESPWROOM32 */
  1989. #elif defined(WOLFSSL_LINUXKM)
  1990. #include <linux/random.h>
  1991. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1992. {
  1993. (void)os;
  1994. get_random_bytes(output, sz);
  1995. return 0;
  1996. }
  1997. #elif defined(WOLFSSL_RENESAS_TSIP)
  1998. #if defined(WOLFSSL_RENESA_TSIP_IAREWRX)
  1999. #include "r_bsp/mcu/all/r_rx_compiler.h"
  2000. #endif
  2001. #include "r_bsp/platform.h"
  2002. #include "r_tsip_rx_if.h"
  2003. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2004. {
  2005. int ret;
  2006. word32 buffer[4];
  2007. while (sz > 0) {
  2008. word32 len = sizeof(buffer);
  2009. if (sz < len) {
  2010. len = sz;
  2011. }
  2012. /* return 4 words random number*/
  2013. ret = R_TSIP_GenerateRandomNumber(buffer);
  2014. if(ret == TSIP_SUCCESS) {
  2015. XMEMCPY(output, &buffer, len);
  2016. output += len;
  2017. sz -= len;
  2018. } else
  2019. return ret;
  2020. }
  2021. return ret;
  2022. }
  2023. #elif defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_TRNG)
  2024. #include "hal_data.h"
  2025. #ifndef WOLFSSL_SCE_TRNG_HANDLE
  2026. #define WOLFSSL_SCE_TRNG_HANDLE g_sce_trng
  2027. #endif
  2028. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2029. {
  2030. word32 ret;
  2031. word32 blocks;
  2032. word32 len = sz;
  2033. ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->open(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl,
  2034. WOLFSSL_SCE_TRNG_HANDLE.p_cfg);
  2035. if (ret != SSP_SUCCESS && ret != SSP_ERR_CRYPTO_ALREADY_OPEN) {
  2036. /* error opening TRNG driver */
  2037. return -1;
  2038. }
  2039. blocks = sz / sizeof(word32);
  2040. if (blocks > 0) {
  2041. ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->read(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl,
  2042. (word32*)output, blocks);
  2043. if (ret != SSP_SUCCESS) {
  2044. return -1;
  2045. }
  2046. }
  2047. len = len - (blocks * sizeof(word32));
  2048. if (len > 0) {
  2049. word32 tmp;
  2050. if (len > sizeof(word32)) {
  2051. return -1;
  2052. }
  2053. ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->read(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl,
  2054. (word32*)tmp, 1);
  2055. if (ret != SSP_SUCCESS) {
  2056. return -1;
  2057. }
  2058. XMEMCPY(output + (blocks * sizeof(word32)), (byte*)&tmp, len);
  2059. }
  2060. ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->close(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl);
  2061. if (ret != SSP_SUCCESS) {
  2062. /* error opening TRNG driver */
  2063. return -1;
  2064. }
  2065. return 0;
  2066. }
  2067. #elif defined(CUSTOM_RAND_GENERATE_BLOCK)
  2068. /* #define CUSTOM_RAND_GENERATE_BLOCK myRngFunc
  2069. * extern int myRngFunc(byte* output, word32 sz);
  2070. */
  2071. #elif defined(WOLFSSL_SAFERTOS) || defined(WOLFSSL_LEANPSK) || \
  2072. defined(WOLFSSL_IAR_ARM) || defined(WOLFSSL_MDK_ARM) || \
  2073. defined(WOLFSSL_uITRON4) || defined(WOLFSSL_uTKERNEL2) || \
  2074. defined(WOLFSSL_LPC43xx) || defined(WOLFSSL_STM32F2xx) || \
  2075. defined(MBED) || defined(WOLFSSL_EMBOS) || \
  2076. defined(WOLFSSL_GENSEED_FORTEST) || defined(WOLFSSL_CHIBIOS) || \
  2077. defined(WOLFSSL_CONTIKI) || defined(WOLFSSL_AZSPHERE)
  2078. /* these platforms do not have a default random seed and
  2079. you'll need to implement your own wc_GenerateSeed or define via
  2080. CUSTOM_RAND_GENERATE_BLOCK */
  2081. #define USE_TEST_GENSEED
  2082. #elif defined(WOLFSSL_ZEPHYR)
  2083. #include <entropy.h>
  2084. #ifndef _POSIX_C_SOURCE
  2085. #include <posix/time.h>
  2086. #else
  2087. #include <sys/time.h>
  2088. #endif
  2089. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2090. {
  2091. int ret = 0;
  2092. word32 rand;
  2093. while (sz > 0) {
  2094. word32 len = sizeof(rand);
  2095. if (sz < len)
  2096. len = sz;
  2097. rand = sys_rand32_get();
  2098. XMEMCPY(output, &rand, len);
  2099. output += len;
  2100. sz -= len;
  2101. }
  2102. return ret;
  2103. }
  2104. #elif defined(WOLFSSL_TELIT_M2MB)
  2105. #include "stdlib.h"
  2106. static long get_timestamp(void) {
  2107. long myTime = 0;
  2108. INT32 fd = m2mb_rtc_open("/dev/rtc0", 0);
  2109. if (fd >= 0) {
  2110. M2MB_RTC_TIMEVAL_T timeval;
  2111. m2mb_rtc_ioctl(fd, M2MB_RTC_IOCTL_GET_TIMEVAL, &timeval);
  2112. myTime = timeval.msec;
  2113. m2mb_rtc_close(fd);
  2114. }
  2115. return myTime;
  2116. }
  2117. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2118. {
  2119. int i;
  2120. srand(get_timestamp());
  2121. for (i = 0; i < sz; i++ ) {
  2122. output[i] = rand() % 256;
  2123. if ((i % 8) == 7) {
  2124. srand(get_timestamp());
  2125. }
  2126. }
  2127. return 0;
  2128. }
  2129. #elif defined(NO_DEV_RANDOM)
  2130. #error "you need to write an os specific wc_GenerateSeed() here"
  2131. /*
  2132. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2133. {
  2134. return 0;
  2135. }
  2136. */
  2137. #else
  2138. /* may block */
  2139. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2140. {
  2141. int ret = 0;
  2142. if (os == NULL) {
  2143. return BAD_FUNC_ARG;
  2144. }
  2145. #ifdef WOLF_CRYPTO_CB
  2146. if (os->devId != INVALID_DEVID) {
  2147. ret = wc_CryptoCb_RandomSeed(os, output, sz);
  2148. if (ret != CRYPTOCB_UNAVAILABLE)
  2149. return ret;
  2150. /* fall-through when unavailable */
  2151. ret = 0; /* reset error code */
  2152. }
  2153. #endif
  2154. #ifdef HAVE_INTEL_RDSEED
  2155. if (IS_INTEL_RDSEED(intel_flags)) {
  2156. ret = wc_GenerateSeed_IntelRD(NULL, output, sz);
  2157. if (ret == 0) {
  2158. /* success, we're done */
  2159. return ret;
  2160. }
  2161. #ifdef FORCE_FAILURE_RDSEED
  2162. /* don't fallback to /dev/urandom */
  2163. return ret;
  2164. #else
  2165. /* reset error and fallback to using /dev/urandom */
  2166. ret = 0;
  2167. #endif
  2168. }
  2169. #endif /* HAVE_INTEL_RDSEED */
  2170. #ifndef NO_DEV_URANDOM /* way to disable use of /dev/urandom */
  2171. os->fd = open("/dev/urandom", O_RDONLY);
  2172. if (os->fd == -1)
  2173. #endif
  2174. {
  2175. /* may still have /dev/random */
  2176. os->fd = open("/dev/random", O_RDONLY);
  2177. if (os->fd == -1)
  2178. return OPEN_RAN_E;
  2179. }
  2180. while (sz) {
  2181. int len = (int)read(os->fd, output, sz);
  2182. if (len == -1) {
  2183. ret = READ_RAN_E;
  2184. break;
  2185. }
  2186. sz -= len;
  2187. output += len;
  2188. if (sz) {
  2189. #if defined(BLOCKING) || defined(WC_RNG_BLOCKING)
  2190. sleep(0); /* context switch */
  2191. #else
  2192. ret = RAN_BLOCK_E;
  2193. break;
  2194. #endif
  2195. }
  2196. }
  2197. close(os->fd);
  2198. return ret;
  2199. }
  2200. #endif
  2201. #ifdef USE_TEST_GENSEED
  2202. #ifndef _MSC_VER
  2203. #warning "write a real random seed!!!!, just for testing now"
  2204. #else
  2205. #pragma message("Warning: write a real random seed!!!!, just for testing now")
  2206. #endif
  2207. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  2208. {
  2209. word32 i;
  2210. for (i = 0; i < sz; i++ )
  2211. output[i] = i;
  2212. (void)os;
  2213. return 0;
  2214. }
  2215. #endif
  2216. /* End wc_GenerateSeed */
  2217. #endif /* WC_NO_RNG */
  2218. #endif /* HAVE_FIPS */