random.c 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041
  1. /* random.c
  2. *
  3. * Copyright (C) 2006-2017 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. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <wolfssl/wolfcrypt/settings.h>
  25. #include <wolfssl/wolfcrypt/error-crypt.h>
  26. /* on HPUX 11 you may need to install /dev/random see
  27. http://h20293.www2.hp.com/portal/swdepot/displayProductInfo.do?productNumber=KRNG11I
  28. */
  29. #if defined(HAVE_FIPS) && \
  30. defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)
  31. /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */
  32. #define FIPS_NO_WRAPPERS
  33. #ifdef USE_WINDOWS_API
  34. #pragma code_seg(".fipsA$c")
  35. #pragma const_seg(".fipsB$c")
  36. #endif
  37. #endif
  38. #include <wolfssl/wolfcrypt/random.h>
  39. #include <wolfssl/wolfcrypt/cpuid.h>
  40. /* If building for old FIPS. */
  41. #if defined(HAVE_FIPS) && \
  42. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2))
  43. int wc_GenerateSeed(OS_Seed* os, byte* seed, word32 sz)
  44. {
  45. return GenerateSeed(os, seed, sz);
  46. }
  47. int wc_InitRng_ex(WC_RNG* rng, void* heap, int devId)
  48. {
  49. (void)heap;
  50. (void)devId;
  51. return InitRng_fips(rng);
  52. }
  53. int wc_InitRng(WC_RNG* rng)
  54. {
  55. return InitRng_fips(rng);
  56. }
  57. int wc_RNG_GenerateBlock(WC_RNG* rng, byte* b, word32 sz)
  58. {
  59. return RNG_GenerateBlock_fips(rng, b, sz);
  60. }
  61. int wc_RNG_GenerateByte(WC_RNG* rng, byte* b)
  62. {
  63. return RNG_GenerateByte(rng, b);
  64. }
  65. #ifdef HAVE_HASHDRBG
  66. int wc_FreeRng(WC_RNG* rng)
  67. {
  68. return FreeRng_fips(rng);
  69. }
  70. int wc_RNG_HealthTest(int reseed,
  71. const byte* entropyA, word32 entropyASz,
  72. const byte* entropyB, word32 entropyBSz,
  73. byte* output, word32 outputSz)
  74. {
  75. return RNG_HealthTest_fips(reseed, entropyA, entropyASz,
  76. entropyB, entropyBSz, output, outputSz);
  77. }
  78. #endif /* HAVE_HASHDRBG */
  79. #else /* else build without fips, or for new fips */
  80. #ifndef WC_NO_RNG /* if not FIPS and RNG is disabled then do not compile */
  81. #include <wolfssl/wolfcrypt/sha256.h>
  82. #ifdef NO_INLINE
  83. #include <wolfssl/wolfcrypt/misc.h>
  84. #else
  85. #define WOLFSSL_MISC_INCLUDED
  86. #include <wolfcrypt/src/misc.c>
  87. #endif
  88. #if defined(WOLFSSL_SGX)
  89. #include <sgx_trts.h>
  90. #elif defined(USE_WINDOWS_API)
  91. #ifndef _WIN32_WINNT
  92. #define _WIN32_WINNT 0x0400
  93. #endif
  94. #include <windows.h>
  95. #include <wincrypt.h>
  96. #elif defined(HAVE_WNR)
  97. #include <wnr.h>
  98. #include <wolfssl/wolfcrypt/logging.h>
  99. wolfSSL_Mutex wnr_mutex; /* global netRandom mutex */
  100. int wnr_timeout = 0; /* entropy timeout, mililseconds */
  101. int wnr_mutex_init = 0; /* flag for mutex init */
  102. wnr_context* wnr_ctx; /* global netRandom context */
  103. #elif defined(FREESCALE_KSDK_2_0_TRNG)
  104. #include "fsl_trng.h"
  105. #elif defined(FREESCALE_KSDK_2_0_RNGA)
  106. #include "fsl_rnga.h"
  107. #elif defined(NO_DEV_RANDOM)
  108. #elif defined(CUSTOM_RAND_GENERATE)
  109. #elif defined(CUSTOM_RAND_GENERATE_BLOCK)
  110. #elif defined(CUSTOM_RAND_GENERATE_SEED)
  111. #elif defined(WOLFSSL_GENSEED_FORTEST)
  112. #elif defined(WOLFSSL_MDK_ARM)
  113. #elif defined(WOLFSSL_IAR_ARM)
  114. #elif defined(WOLFSSL_ROWLEY_ARM)
  115. #elif defined(WOLFSSL_EMBOS)
  116. #elif defined(MICRIUM)
  117. #elif defined(WOLFSSL_NUCLEUS)
  118. #elif defined(WOLFSSL_PB)
  119. #else
  120. /* include headers that may be needed to get good seed */
  121. #include <fcntl.h>
  122. #ifndef EBSNET
  123. #include <unistd.h>
  124. #endif
  125. #endif
  126. #if defined(HAVE_INTEL_RDRAND) || defined(HAVE_INTEL_RDSEED)
  127. static word32 intel_flags = 0;
  128. static void wc_InitRng_IntelRD(void)
  129. {
  130. intel_flags = cpuid_get_flags();
  131. }
  132. #ifdef HAVE_INTEL_RDSEED
  133. static int wc_GenerateSeed_IntelRD(OS_Seed* os, byte* output, word32 sz);
  134. #endif
  135. #ifdef HAVE_INTEL_RDRAND
  136. static int wc_GenerateRand_IntelRD(OS_Seed* os, byte* output, word32 sz);
  137. #endif
  138. #ifdef USE_WINDOWS_API
  139. #include <immintrin.h>
  140. #endif /* USE_WINDOWS_API */
  141. #endif
  142. /* Start NIST DRBG code */
  143. #ifdef HAVE_HASHDRBG
  144. #define OUTPUT_BLOCK_LEN (WC_SHA256_DIGEST_SIZE)
  145. #define MAX_REQUEST_LEN (0x10000)
  146. #define RESEED_INTERVAL WC_RESEED_INTERVAL
  147. #define SECURITY_STRENGTH (2048)
  148. #define ENTROPY_SZ (SECURITY_STRENGTH/8)
  149. #define MAX_ENTROPY_SZ (ENTROPY_SZ + ENTROPY_SZ/2)
  150. /* Internal return codes */
  151. #define DRBG_SUCCESS 0
  152. #define DRBG_FAILURE 1
  153. #define DRBG_NEED_RESEED 2
  154. #define DRBG_CONT_FAILURE 3
  155. /* RNG health states */
  156. #define DRBG_NOT_INIT 0
  157. #define DRBG_OK 1
  158. #define DRBG_FAILED 2
  159. #define DRBG_CONT_FAILED 3
  160. #define RNG_HEALTH_TEST_CHECK_SIZE (WC_SHA256_DIGEST_SIZE * 4)
  161. /* Verify max gen block len */
  162. #if RNG_MAX_BLOCK_LEN > MAX_REQUEST_LEN
  163. #error RNG_MAX_BLOCK_LEN is larger than NIST DBRG max request length
  164. #endif
  165. enum {
  166. drbgInitC = 0,
  167. drbgReseed = 1,
  168. drbgGenerateW = 2,
  169. drbgGenerateH = 3,
  170. drbgInitV
  171. };
  172. typedef struct DRBG {
  173. word32 reseedCtr;
  174. word32 lastBlock;
  175. byte V[DRBG_SEED_LEN];
  176. byte C[DRBG_SEED_LEN];
  177. #ifdef WOLFSSL_ASYNC_CRYPT
  178. void* heap;
  179. int devId;
  180. #endif
  181. byte matchCount;
  182. #ifdef WOLFSSL_SMALL_STACK_CACHE
  183. wc_Sha256 sha256;
  184. #endif
  185. } DRBG;
  186. static int wc_RNG_HealthTestLocal(int reseed);
  187. /* Hash Derivation Function */
  188. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  189. static int Hash_df(DRBG* drbg, byte* out, word32 outSz, byte type,
  190. const byte* inA, word32 inASz,
  191. const byte* inB, word32 inBSz)
  192. {
  193. int ret = DRBG_FAILURE;
  194. byte ctr;
  195. int i;
  196. int len;
  197. word32 bits = (outSz * 8); /* reverse byte order */
  198. #ifdef WOLFSSL_SMALL_STACK_CACHE
  199. wc_Sha256* sha = &drbg->sha256;
  200. #else
  201. wc_Sha256 sha[1];
  202. #endif
  203. DECLARE_VAR(digest, byte, WC_SHA256_DIGEST_SIZE, drbg->heap);
  204. (void)drbg;
  205. #ifdef WOLFSSL_ASYNC_CRYPT
  206. if (digest == NULL)
  207. return DRBG_FAILURE;
  208. #endif
  209. #ifdef LITTLE_ENDIAN_ORDER
  210. bits = ByteReverseWord32(bits);
  211. #endif
  212. len = (outSz / OUTPUT_BLOCK_LEN)
  213. + ((outSz % OUTPUT_BLOCK_LEN) ? 1 : 0);
  214. for (i = 0, ctr = 1; i < len; i++, ctr++) {
  215. #ifndef WOLFSSL_SMALL_STACK_CACHE
  216. #ifdef WOLFSSL_ASYNC_CRYPT
  217. ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId);
  218. #else
  219. ret = wc_InitSha256(sha);
  220. #endif
  221. if (ret != 0)
  222. break;
  223. if (ret == 0)
  224. #endif
  225. ret = wc_Sha256Update(sha, &ctr, sizeof(ctr));
  226. if (ret == 0)
  227. ret = wc_Sha256Update(sha, (byte*)&bits, sizeof(bits));
  228. if (ret == 0) {
  229. /* churning V is the only string that doesn't have the type added */
  230. if (type != drbgInitV)
  231. ret = wc_Sha256Update(sha, &type, sizeof(type));
  232. }
  233. if (ret == 0)
  234. ret = wc_Sha256Update(sha, inA, inASz);
  235. if (ret == 0) {
  236. if (inB != NULL && inBSz > 0)
  237. ret = wc_Sha256Update(sha, inB, inBSz);
  238. }
  239. if (ret == 0)
  240. ret = wc_Sha256Final(sha, digest);
  241. #ifndef WOLFSSL_SMALL_STACK_CACHE
  242. wc_Sha256Free(sha);
  243. #endif
  244. if (ret == 0) {
  245. if (outSz > OUTPUT_BLOCK_LEN) {
  246. XMEMCPY(out, digest, OUTPUT_BLOCK_LEN);
  247. outSz -= OUTPUT_BLOCK_LEN;
  248. out += OUTPUT_BLOCK_LEN;
  249. }
  250. else {
  251. XMEMCPY(out, digest, outSz);
  252. }
  253. }
  254. }
  255. ForceZero(digest, WC_SHA256_DIGEST_SIZE);
  256. FREE_VAR(digest, drbg->heap);
  257. return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
  258. }
  259. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  260. static int Hash_DRBG_Reseed(DRBG* drbg, const byte* entropy, word32 entropySz)
  261. {
  262. byte seed[DRBG_SEED_LEN];
  263. if (Hash_df(drbg, seed, sizeof(seed), drbgReseed, drbg->V, sizeof(drbg->V),
  264. entropy, entropySz) != DRBG_SUCCESS) {
  265. return DRBG_FAILURE;
  266. }
  267. XMEMCPY(drbg->V, seed, sizeof(drbg->V));
  268. ForceZero(seed, sizeof(seed));
  269. if (Hash_df(drbg, drbg->C, sizeof(drbg->C), drbgInitC, drbg->V,
  270. sizeof(drbg->V), NULL, 0) != DRBG_SUCCESS) {
  271. return DRBG_FAILURE;
  272. }
  273. drbg->reseedCtr = 1;
  274. drbg->lastBlock = 0;
  275. drbg->matchCount = 0;
  276. return DRBG_SUCCESS;
  277. }
  278. /* Returns: DRBG_SUCCESS and DRBG_FAILURE or BAD_FUNC_ARG on fail */
  279. int wc_RNG_DRBG_Reseed(WC_RNG* rng, const byte* entropy, word32 entropySz)
  280. {
  281. if (rng == NULL || entropy == NULL) {
  282. return BAD_FUNC_ARG;
  283. }
  284. return Hash_DRBG_Reseed(rng->drbg, entropy, entropySz);
  285. }
  286. static WC_INLINE void array_add_one(byte* data, word32 dataSz)
  287. {
  288. int i;
  289. for (i = dataSz - 1; i >= 0; i--)
  290. {
  291. data[i]++;
  292. if (data[i] != 0) break;
  293. }
  294. }
  295. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  296. static int Hash_gen(DRBG* drbg, byte* out, word32 outSz, const byte* V)
  297. {
  298. int ret = DRBG_FAILURE;
  299. byte data[DRBG_SEED_LEN];
  300. int i;
  301. int len;
  302. word32 checkBlock;
  303. #ifdef WOLFSSL_SMALL_STACK_CACHE
  304. wc_Sha256* sha = &drbg->sha256;
  305. #else
  306. wc_Sha256 sha[1];
  307. #endif
  308. DECLARE_VAR(digest, byte, WC_SHA256_DIGEST_SIZE, drbg->heap);
  309. /* Special case: outSz is 0 and out is NULL. wc_Generate a block to save for
  310. * the continuous test. */
  311. if (outSz == 0) outSz = 1;
  312. len = (outSz / OUTPUT_BLOCK_LEN) + ((outSz % OUTPUT_BLOCK_LEN) ? 1 : 0);
  313. XMEMCPY(data, V, sizeof(data));
  314. for (i = 0; i < len; i++) {
  315. #ifndef WOLFSSL_SMALL_STACK_CACHE
  316. #ifdef WOLFSSL_ASYNC_CRYPT
  317. ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId);
  318. #else
  319. ret = wc_InitSha256(sha);
  320. #endif
  321. if (ret == 0)
  322. #endif
  323. ret = wc_Sha256Update(sha, data, sizeof(data));
  324. if (ret == 0)
  325. ret = wc_Sha256Final(sha, digest);
  326. #ifndef WOLFSSL_SMALL_STACK_CACHE
  327. wc_Sha256Free(sha);
  328. #endif
  329. if (ret == 0) {
  330. XMEMCPY(&checkBlock, digest, sizeof(word32));
  331. if (drbg->reseedCtr > 1 && checkBlock == drbg->lastBlock) {
  332. if (drbg->matchCount == 1) {
  333. return DRBG_CONT_FAILURE;
  334. }
  335. else {
  336. if (i == len) {
  337. len++;
  338. }
  339. drbg->matchCount = 1;
  340. }
  341. }
  342. else {
  343. drbg->matchCount = 0;
  344. drbg->lastBlock = checkBlock;
  345. }
  346. if (out != NULL && outSz != 0) {
  347. if (outSz >= OUTPUT_BLOCK_LEN) {
  348. XMEMCPY(out, digest, OUTPUT_BLOCK_LEN);
  349. outSz -= OUTPUT_BLOCK_LEN;
  350. out += OUTPUT_BLOCK_LEN;
  351. array_add_one(data, DRBG_SEED_LEN);
  352. }
  353. else {
  354. XMEMCPY(out, digest, outSz);
  355. outSz = 0;
  356. }
  357. }
  358. }
  359. }
  360. ForceZero(data, sizeof(data));
  361. FREE_VAR(digest, drbg->heap);
  362. return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
  363. }
  364. static WC_INLINE void array_add(byte* d, word32 dLen, const byte* s, word32 sLen)
  365. {
  366. word16 carry = 0;
  367. if (dLen > 0 && sLen > 0 && dLen >= sLen) {
  368. int sIdx, dIdx;
  369. for (sIdx = sLen - 1, dIdx = dLen - 1; sIdx >= 0; dIdx--, sIdx--)
  370. {
  371. carry += d[dIdx] + s[sIdx];
  372. d[dIdx] = (byte)carry;
  373. carry >>= 8;
  374. }
  375. for (; carry != 0 && dIdx >= 0; dIdx--) {
  376. carry += d[dIdx];
  377. d[dIdx] = (byte)carry;
  378. carry >>= 8;
  379. }
  380. }
  381. }
  382. /* Returns: DRBG_SUCCESS, DRBG_NEED_RESEED, or DRBG_FAILURE */
  383. static int Hash_DRBG_Generate(DRBG* drbg, byte* out, word32 outSz)
  384. {
  385. int ret;
  386. #ifdef WOLFSSL_SMALL_STACK_CACHE
  387. wc_Sha256* sha = &drbg->sha256;
  388. #else
  389. wc_Sha256 sha[1];
  390. #endif
  391. byte type;
  392. word32 reseedCtr;
  393. if (drbg->reseedCtr == RESEED_INTERVAL) {
  394. return DRBG_NEED_RESEED;
  395. } else {
  396. DECLARE_VAR(digest, byte, WC_SHA256_DIGEST_SIZE, drbg->heap);
  397. type = drbgGenerateH;
  398. reseedCtr = drbg->reseedCtr;
  399. ret = Hash_gen(drbg, out, outSz, drbg->V);
  400. if (ret == DRBG_SUCCESS) {
  401. #ifndef WOLFSSL_SMALL_STACK_CACHE
  402. #ifdef WOLFSSL_ASYNC_CRYPT
  403. ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId);
  404. #else
  405. ret = wc_InitSha256(sha);
  406. #endif
  407. if (ret == 0)
  408. #endif
  409. ret = wc_Sha256Update(sha, &type, sizeof(type));
  410. if (ret == 0)
  411. ret = wc_Sha256Update(sha, drbg->V, sizeof(drbg->V));
  412. if (ret == 0)
  413. ret = wc_Sha256Final(sha, digest);
  414. #ifndef WOLFSSL_SMALL_STACK_CACHE
  415. wc_Sha256Free(sha);
  416. #endif
  417. if (ret == 0) {
  418. array_add(drbg->V, sizeof(drbg->V), digest, WC_SHA256_DIGEST_SIZE);
  419. array_add(drbg->V, sizeof(drbg->V), drbg->C, sizeof(drbg->C));
  420. #ifdef LITTLE_ENDIAN_ORDER
  421. reseedCtr = ByteReverseWord32(reseedCtr);
  422. #endif
  423. array_add(drbg->V, sizeof(drbg->V),
  424. (byte*)&reseedCtr, sizeof(reseedCtr));
  425. ret = DRBG_SUCCESS;
  426. }
  427. drbg->reseedCtr++;
  428. }
  429. ForceZero(digest, WC_SHA256_DIGEST_SIZE);
  430. FREE_VAR(digest, drbg->heap);
  431. }
  432. return (ret == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
  433. }
  434. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  435. static int Hash_DRBG_Instantiate(DRBG* drbg, const byte* seed, word32 seedSz,
  436. const byte* nonce, word32 nonceSz,
  437. void* heap, int devId)
  438. {
  439. int ret = DRBG_FAILURE;
  440. XMEMSET(drbg, 0, sizeof(DRBG));
  441. #ifdef WOLFSSL_ASYNC_CRYPT
  442. drbg->heap = heap;
  443. drbg->devId = devId;
  444. #else
  445. (void)heap;
  446. (void)devId;
  447. #endif
  448. #ifdef WOLFSSL_SMALL_STACK_CACHE
  449. #ifdef WOLFSSL_ASYNC_CRYPT
  450. ret = wc_InitSha256_ex(&drbg->sha256, drbg->heap, drbg->devId);
  451. #else
  452. ret = wc_InitSha256(&drbg->sha256);
  453. #endif
  454. if (ret != 0)
  455. return ret;
  456. #endif
  457. if (Hash_df(drbg, drbg->V, sizeof(drbg->V), drbgInitV, seed, seedSz,
  458. nonce, nonceSz) == DRBG_SUCCESS &&
  459. Hash_df(drbg, drbg->C, sizeof(drbg->C), drbgInitC, drbg->V,
  460. sizeof(drbg->V), NULL, 0) == DRBG_SUCCESS) {
  461. drbg->reseedCtr = 1;
  462. drbg->lastBlock = 0;
  463. drbg->matchCount = 0;
  464. ret = DRBG_SUCCESS;
  465. }
  466. return ret;
  467. }
  468. /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
  469. static int Hash_DRBG_Uninstantiate(DRBG* drbg)
  470. {
  471. word32 i;
  472. int compareSum = 0;
  473. byte* compareDrbg = (byte*)drbg;
  474. #ifdef WOLFSSL_SMALL_STACK_CACHE
  475. wc_Sha256Free(&drbg->sha256);
  476. #endif
  477. ForceZero(drbg, sizeof(DRBG));
  478. for (i = 0; i < sizeof(DRBG); i++)
  479. compareSum |= compareDrbg[i] ^ 0;
  480. return (compareSum == 0) ? DRBG_SUCCESS : DRBG_FAILURE;
  481. }
  482. #endif /* HAVE_HASHDRBG */
  483. /* End NIST DRBG Code */
  484. static int _InitRng(WC_RNG* rng, byte* nonce, word32 nonceSz,
  485. void* heap, int devId)
  486. {
  487. int ret = RNG_FAILURE_E;
  488. #ifdef HAVE_HASHDRBG
  489. word32 entropySz = ENTROPY_SZ;
  490. #endif
  491. (void)nonce;
  492. (void)nonceSz;
  493. if (rng == NULL)
  494. return BAD_FUNC_ARG;
  495. if (nonce == NULL && nonceSz != 0)
  496. return BAD_FUNC_ARG;
  497. #ifdef WOLFSSL_HEAP_TEST
  498. rng->heap = (void*)WOLFSSL_HEAP_TEST;
  499. (void)heap;
  500. #else
  501. rng->heap = heap;
  502. #endif
  503. #ifdef WOLFSSL_ASYNC_CRYPT
  504. rng->devId = devId;
  505. #else
  506. (void)devId;
  507. #endif
  508. #ifdef HAVE_HASHDRBG
  509. /* init the DBRG to known values */
  510. rng->drbg = NULL;
  511. rng->status = DRBG_NOT_INIT;
  512. #endif
  513. #if defined(HAVE_INTEL_RDSEED) || defined(HAVE_INTEL_RDRAND)
  514. /* init the intel RD seed and/or rand */
  515. wc_InitRng_IntelRD();
  516. #endif
  517. /* configure async RNG source if available */
  518. #ifdef WOLFSSL_ASYNC_CRYPT
  519. ret = wolfAsync_DevCtxInit(&rng->asyncDev, WOLFSSL_ASYNC_MARKER_RNG,
  520. rng->heap, rng->devId);
  521. if (ret != 0)
  522. return ret;
  523. #endif
  524. #ifdef HAVE_INTEL_RDRAND
  525. /* if CPU supports RDRAND, use it directly and by-pass DRBG init */
  526. if (IS_INTEL_RDRAND(intel_flags))
  527. return 0;
  528. #endif
  529. #ifdef CUSTOM_RAND_GENERATE_BLOCK
  530. ret = 0; /* success */
  531. #else
  532. #ifdef HAVE_HASHDRBG
  533. if (nonceSz == 0)
  534. entropySz = MAX_ENTROPY_SZ;
  535. if (wc_RNG_HealthTestLocal(0) == 0) {
  536. DECLARE_VAR(entropy, byte, MAX_ENTROPY_SZ, rng->heap);
  537. rng->drbg =
  538. (struct DRBG*)XMALLOC(sizeof(DRBG), rng->heap,
  539. DYNAMIC_TYPE_RNG);
  540. if (rng->drbg == NULL) {
  541. ret = MEMORY_E;
  542. }
  543. else if (wc_GenerateSeed(&rng->seed, entropy, entropySz) == 0 &&
  544. Hash_DRBG_Instantiate(rng->drbg, entropy, entropySz,
  545. nonce, nonceSz, rng->heap, devId) == DRBG_SUCCESS) {
  546. ret = Hash_DRBG_Generate(rng->drbg, NULL, 0);
  547. }
  548. else
  549. ret = DRBG_FAILURE;
  550. ForceZero(entropy, entropySz);
  551. FREE_VAR(entropy, rng->heap);
  552. }
  553. else
  554. ret = DRBG_CONT_FAILURE;
  555. if (ret == DRBG_SUCCESS) {
  556. rng->status = DRBG_OK;
  557. ret = 0;
  558. }
  559. else if (ret == DRBG_CONT_FAILURE) {
  560. rng->status = DRBG_CONT_FAILED;
  561. ret = DRBG_CONT_FIPS_E;
  562. }
  563. else if (ret == DRBG_FAILURE) {
  564. rng->status = DRBG_FAILED;
  565. ret = RNG_FAILURE_E;
  566. }
  567. else {
  568. rng->status = DRBG_FAILED;
  569. }
  570. #endif /* HAVE_HASHDRBG */
  571. #endif /* CUSTOM_RAND_GENERATE_BLOCK */
  572. return ret;
  573. }
  574. int wc_InitRng(WC_RNG* rng)
  575. {
  576. return _InitRng(rng, NULL, 0, NULL, INVALID_DEVID);
  577. }
  578. int wc_InitRng_ex(WC_RNG* rng, void* heap, int devId)
  579. {
  580. return _InitRng(rng, NULL, 0, heap, devId);
  581. }
  582. int wc_InitRngNonce(WC_RNG* rng, byte* nonce, word32 nonceSz)
  583. {
  584. return _InitRng(rng, nonce, nonceSz, NULL, INVALID_DEVID);
  585. }
  586. int wc_InitRngNonce_ex(WC_RNG* rng, byte* nonce, word32 nonceSz,
  587. void* heap, int devId)
  588. {
  589. return _InitRng(rng, nonce, nonceSz, heap, devId);
  590. }
  591. /* place a generated block in output */
  592. int wc_RNG_GenerateBlock(WC_RNG* rng, byte* output, word32 sz)
  593. {
  594. int ret;
  595. if (rng == NULL || output == NULL)
  596. return BAD_FUNC_ARG;
  597. #ifdef HAVE_INTEL_RDRAND
  598. if (IS_INTEL_RDRAND(intel_flags))
  599. return wc_GenerateRand_IntelRD(NULL, output, sz);
  600. #endif
  601. #if defined(WOLFSSL_ASYNC_CRYPT)
  602. if (rng->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RNG) {
  603. /* these are blocking */
  604. #ifdef HAVE_CAVIUM
  605. return NitroxRngGenerateBlock(rng, output, sz);
  606. #elif defined(HAVE_INTEL_QA)
  607. return IntelQaDrbg(&rng->asyncDev, output, sz);
  608. #else
  609. /* simulator not supported */
  610. #endif
  611. }
  612. #endif
  613. #ifdef CUSTOM_RAND_GENERATE_BLOCK
  614. XMEMSET(output, 0, sz);
  615. ret = CUSTOM_RAND_GENERATE_BLOCK(output, sz);
  616. #else
  617. #ifdef HAVE_HASHDRBG
  618. if (sz > RNG_MAX_BLOCK_LEN)
  619. return BAD_FUNC_ARG;
  620. if (rng->status != DRBG_OK)
  621. return RNG_FAILURE_E;
  622. ret = Hash_DRBG_Generate(rng->drbg, output, sz);
  623. if (ret == DRBG_NEED_RESEED) {
  624. if (wc_RNG_HealthTestLocal(1) == 0) {
  625. byte entropy[ENTROPY_SZ];
  626. if (wc_GenerateSeed(&rng->seed, entropy, ENTROPY_SZ) == 0 &&
  627. Hash_DRBG_Reseed(rng->drbg, entropy, ENTROPY_SZ)
  628. == DRBG_SUCCESS) {
  629. ret = Hash_DRBG_Generate(rng->drbg, NULL, 0);
  630. if (ret == DRBG_SUCCESS)
  631. ret = Hash_DRBG_Generate(rng->drbg, output, sz);
  632. }
  633. else
  634. ret = DRBG_FAILURE;
  635. ForceZero(entropy, ENTROPY_SZ);
  636. }
  637. else
  638. ret = DRBG_CONT_FAILURE;
  639. }
  640. if (ret == DRBG_SUCCESS) {
  641. ret = 0;
  642. }
  643. else if (ret == DRBG_CONT_FAILURE) {
  644. ret = DRBG_CONT_FIPS_E;
  645. rng->status = DRBG_CONT_FAILED;
  646. }
  647. else {
  648. ret = RNG_FAILURE_E;
  649. rng->status = DRBG_FAILED;
  650. }
  651. #else
  652. /* if we get here then there is an RNG configuration error */
  653. ret = RNG_FAILURE_E;
  654. #endif /* HAVE_HASHDRBG */
  655. #endif /* CUSTOM_RAND_GENERATE_BLOCK */
  656. return ret;
  657. }
  658. int wc_RNG_GenerateByte(WC_RNG* rng, byte* b)
  659. {
  660. return wc_RNG_GenerateBlock(rng, b, 1);
  661. }
  662. int wc_FreeRng(WC_RNG* rng)
  663. {
  664. int ret = 0;
  665. if (rng == NULL)
  666. return BAD_FUNC_ARG;
  667. #if defined(WOLFSSL_ASYNC_CRYPT)
  668. wolfAsync_DevCtxFree(&rng->asyncDev, WOLFSSL_ASYNC_MARKER_RNG);
  669. #endif
  670. #ifdef HAVE_HASHDRBG
  671. if (rng->drbg != NULL) {
  672. if (Hash_DRBG_Uninstantiate(rng->drbg) != DRBG_SUCCESS)
  673. ret = RNG_FAILURE_E;
  674. XFREE(rng->drbg, rng->heap, DYNAMIC_TYPE_RNG);
  675. rng->drbg = NULL;
  676. }
  677. rng->status = DRBG_NOT_INIT;
  678. #endif /* HAVE_HASHDRBG */
  679. return ret;
  680. }
  681. #ifdef HAVE_HASHDRBG
  682. int wc_RNG_HealthTest(int reseed, const byte* entropyA, word32 entropyASz,
  683. const byte* entropyB, word32 entropyBSz,
  684. byte* output, word32 outputSz)
  685. {
  686. return wc_RNG_HealthTest_ex(reseed, NULL, 0,
  687. entropyA, entropyASz,
  688. entropyB, entropyBSz,
  689. output, outputSz,
  690. NULL, INVALID_DEVID);
  691. }
  692. int wc_RNG_HealthTest_ex(int reseed, const byte* nonce, word32 nonceSz,
  693. const byte* entropyA, word32 entropyASz,
  694. const byte* entropyB, word32 entropyBSz,
  695. byte* output, word32 outputSz,
  696. void* heap, int devId)
  697. {
  698. int ret = -1;
  699. DRBG* drbg;
  700. #ifndef WOLFSSL_SMALL_STACK
  701. DRBG drbg_var;
  702. #endif
  703. if (entropyA == NULL || output == NULL) {
  704. return BAD_FUNC_ARG;
  705. }
  706. if (reseed != 0 && entropyB == NULL) {
  707. return BAD_FUNC_ARG;
  708. }
  709. if (outputSz != RNG_HEALTH_TEST_CHECK_SIZE) {
  710. return ret;
  711. }
  712. #ifdef WOLFSSL_SMALL_STACK
  713. drbg = (struct DRBG*)XMALLOC(sizeof(DRBG), NULL, DYNAMIC_TYPE_RNG);
  714. if (drbg == NULL) {
  715. return MEMORY_E;
  716. }
  717. #else
  718. drbg = &drbg_var;
  719. #endif
  720. if (Hash_DRBG_Instantiate(drbg, entropyA, entropyASz, nonce, nonceSz,
  721. heap, devId) != 0) {
  722. goto exit_rng_ht;
  723. }
  724. if (reseed) {
  725. if (Hash_DRBG_Reseed(drbg, entropyB, entropyBSz) != 0) {
  726. goto exit_rng_ht;
  727. }
  728. }
  729. if (Hash_DRBG_Generate(drbg, output, outputSz) != 0) {
  730. goto exit_rng_ht;
  731. }
  732. if (Hash_DRBG_Generate(drbg, output, outputSz) != 0) {
  733. goto exit_rng_ht;
  734. }
  735. /* Mark success */
  736. ret = 0;
  737. exit_rng_ht:
  738. /* This is safe to call even if Hash_DRBG_Instantiate fails */
  739. if (Hash_DRBG_Uninstantiate(drbg) != 0) {
  740. ret = -1;
  741. }
  742. #ifdef WOLFSSL_SMALL_STACK
  743. XFREE(drbg, NULL, DYNAMIC_TYPE_RNG);
  744. #endif
  745. return ret;
  746. }
  747. const byte entropyA[] = {
  748. 0x63, 0x36, 0x33, 0x77, 0xe4, 0x1e, 0x86, 0x46, 0x8d, 0xeb, 0x0a, 0xb4,
  749. 0xa8, 0xed, 0x68, 0x3f, 0x6a, 0x13, 0x4e, 0x47, 0xe0, 0x14, 0xc7, 0x00,
  750. 0x45, 0x4e, 0x81, 0xe9, 0x53, 0x58, 0xa5, 0x69, 0x80, 0x8a, 0xa3, 0x8f,
  751. 0x2a, 0x72, 0xa6, 0x23, 0x59, 0x91, 0x5a, 0x9f, 0x8a, 0x04, 0xca, 0x68
  752. };
  753. const byte reseedEntropyA[] = {
  754. 0xe6, 0x2b, 0x8a, 0x8e, 0xe8, 0xf1, 0x41, 0xb6, 0x98, 0x05, 0x66, 0xe3,
  755. 0xbf, 0xe3, 0xc0, 0x49, 0x03, 0xda, 0xd4, 0xac, 0x2c, 0xdf, 0x9f, 0x22,
  756. 0x80, 0x01, 0x0a, 0x67, 0x39, 0xbc, 0x83, 0xd3
  757. };
  758. const byte outputA[] = {
  759. 0x04, 0xee, 0xc6, 0x3b, 0xb2, 0x31, 0xdf, 0x2c, 0x63, 0x0a, 0x1a, 0xfb,
  760. 0xe7, 0x24, 0x94, 0x9d, 0x00, 0x5a, 0x58, 0x78, 0x51, 0xe1, 0xaa, 0x79,
  761. 0x5e, 0x47, 0x73, 0x47, 0xc8, 0xb0, 0x56, 0x62, 0x1c, 0x18, 0xbd, 0xdc,
  762. 0xdd, 0x8d, 0x99, 0xfc, 0x5f, 0xc2, 0xb9, 0x20, 0x53, 0xd8, 0xcf, 0xac,
  763. 0xfb, 0x0b, 0xb8, 0x83, 0x12, 0x05, 0xfa, 0xd1, 0xdd, 0xd6, 0xc0, 0x71,
  764. 0x31, 0x8a, 0x60, 0x18, 0xf0, 0x3b, 0x73, 0xf5, 0xed, 0xe4, 0xd4, 0xd0,
  765. 0x71, 0xf9, 0xde, 0x03, 0xfd, 0x7a, 0xea, 0x10, 0x5d, 0x92, 0x99, 0xb8,
  766. 0xaf, 0x99, 0xaa, 0x07, 0x5b, 0xdb, 0x4d, 0xb9, 0xaa, 0x28, 0xc1, 0x8d,
  767. 0x17, 0x4b, 0x56, 0xee, 0x2a, 0x01, 0x4d, 0x09, 0x88, 0x96, 0xff, 0x22,
  768. 0x82, 0xc9, 0x55, 0xa8, 0x19, 0x69, 0xe0, 0x69, 0xfa, 0x8c, 0xe0, 0x07,
  769. 0xa1, 0x80, 0x18, 0x3a, 0x07, 0xdf, 0xae, 0x17
  770. };
  771. const byte entropyB[] = {
  772. 0xa6, 0x5a, 0xd0, 0xf3, 0x45, 0xdb, 0x4e, 0x0e, 0xff, 0xe8, 0x75, 0xc3,
  773. 0xa2, 0xe7, 0x1f, 0x42, 0xc7, 0x12, 0x9d, 0x62, 0x0f, 0xf5, 0xc1, 0x19,
  774. 0xa9, 0xef, 0x55, 0xf0, 0x51, 0x85, 0xe0, 0xfb, /* nonce next */
  775. 0x85, 0x81, 0xf9, 0x31, 0x75, 0x17, 0x27, 0x6e, 0x06, 0xe9, 0x60, 0x7d,
  776. 0xdb, 0xcb, 0xcc, 0x2e
  777. };
  778. const byte outputB[] = {
  779. 0xd3, 0xe1, 0x60, 0xc3, 0x5b, 0x99, 0xf3, 0x40, 0xb2, 0x62, 0x82, 0x64,
  780. 0xd1, 0x75, 0x10, 0x60, 0xe0, 0x04, 0x5d, 0xa3, 0x83, 0xff, 0x57, 0xa5,
  781. 0x7d, 0x73, 0xa6, 0x73, 0xd2, 0xb8, 0xd8, 0x0d, 0xaa, 0xf6, 0xa6, 0xc3,
  782. 0x5a, 0x91, 0xbb, 0x45, 0x79, 0xd7, 0x3f, 0xd0, 0xc8, 0xfe, 0xd1, 0x11,
  783. 0xb0, 0x39, 0x13, 0x06, 0x82, 0x8a, 0xdf, 0xed, 0x52, 0x8f, 0x01, 0x81,
  784. 0x21, 0xb3, 0xfe, 0xbd, 0xc3, 0x43, 0xe7, 0x97, 0xb8, 0x7d, 0xbb, 0x63,
  785. 0xdb, 0x13, 0x33, 0xde, 0xd9, 0xd1, 0xec, 0xe1, 0x77, 0xcf, 0xa6, 0xb7,
  786. 0x1f, 0xe8, 0xab, 0x1d, 0xa4, 0x66, 0x24, 0xed, 0x64, 0x15, 0xe5, 0x1c,
  787. 0xcd, 0xe2, 0xc7, 0xca, 0x86, 0xe2, 0x83, 0x99, 0x0e, 0xea, 0xeb, 0x91,
  788. 0x12, 0x04, 0x15, 0x52, 0x8b, 0x22, 0x95, 0x91, 0x02, 0x81, 0xb0, 0x2d,
  789. 0xd4, 0x31, 0xf4, 0xc9, 0xf7, 0x04, 0x27, 0xdf
  790. };
  791. static int wc_RNG_HealthTestLocal(int reseed)
  792. {
  793. int ret = 0;
  794. #ifdef WOLFSSL_SMALL_STACK
  795. byte* check;
  796. #else
  797. byte check[RNG_HEALTH_TEST_CHECK_SIZE];
  798. #endif
  799. #ifdef WOLFSSL_SMALL_STACK
  800. check = (byte*)XMALLOC(RNG_HEALTH_TEST_CHECK_SIZE, NULL,
  801. DYNAMIC_TYPE_TMP_BUFFER);
  802. if (check == NULL) {
  803. return MEMORY_E;
  804. }
  805. #endif
  806. if (reseed) {
  807. ret = wc_RNG_HealthTest(1, entropyA, sizeof(entropyA),
  808. reseedEntropyA, sizeof(reseedEntropyA),
  809. check, RNG_HEALTH_TEST_CHECK_SIZE);
  810. if (ret == 0) {
  811. if (ConstantCompare(check, outputA,
  812. RNG_HEALTH_TEST_CHECK_SIZE) != 0)
  813. ret = -1;
  814. }
  815. }
  816. else {
  817. ret = wc_RNG_HealthTest(0, entropyB, sizeof(entropyB),
  818. NULL, 0,
  819. check, RNG_HEALTH_TEST_CHECK_SIZE);
  820. if (ret == 0) {
  821. if (ConstantCompare(check, outputB,
  822. RNG_HEALTH_TEST_CHECK_SIZE) != 0)
  823. ret = -1;
  824. }
  825. /* The previous test cases use a large seed instead of a seed and nonce.
  826. * entropyB is actually from a test case with a seed and nonce, and
  827. * just concatenates them. The pivot point between seed and nonce is
  828. * byte 32, feed them into the health test separately. */
  829. if (ret == 0) {
  830. ret = wc_RNG_HealthTest_ex(0,
  831. entropyB + 32, sizeof(entropyB) - 32,
  832. entropyB, 32,
  833. NULL, 0,
  834. check, RNG_HEALTH_TEST_CHECK_SIZE,
  835. NULL, INVALID_DEVID);
  836. if (ret == 0) {
  837. if (ConstantCompare(check, outputB, sizeof(outputB)) != 0)
  838. ret = -1;
  839. }
  840. }
  841. }
  842. #ifdef WOLFSSL_SMALL_STACK
  843. XFREE(check, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  844. #endif
  845. return ret;
  846. }
  847. #endif /* HAVE_HASHDRBG */
  848. #ifdef HAVE_WNR
  849. /*
  850. * Init global Whitewood netRandom context
  851. * Returns 0 on success, negative on error
  852. */
  853. int wc_InitNetRandom(const char* configFile, wnr_hmac_key hmac_cb, int timeout)
  854. {
  855. if (configFile == NULL || timeout < 0)
  856. return BAD_FUNC_ARG;
  857. if (wnr_mutex_init > 0) {
  858. WOLFSSL_MSG("netRandom context already created, skipping");
  859. return 0;
  860. }
  861. if (wc_InitMutex(&wnr_mutex) != 0) {
  862. WOLFSSL_MSG("Bad Init Mutex wnr_mutex");
  863. return BAD_MUTEX_E;
  864. }
  865. wnr_mutex_init = 1;
  866. if (wc_LockMutex(&wnr_mutex) != 0) {
  867. WOLFSSL_MSG("Bad Lock Mutex wnr_mutex");
  868. return BAD_MUTEX_E;
  869. }
  870. /* store entropy timeout */
  871. wnr_timeout = timeout;
  872. /* create global wnr_context struct */
  873. if (wnr_create(&wnr_ctx) != WNR_ERROR_NONE) {
  874. WOLFSSL_MSG("Error creating global netRandom context");
  875. return RNG_FAILURE_E;
  876. }
  877. /* load config file */
  878. if (wnr_config_loadf(wnr_ctx, (char*)configFile) != WNR_ERROR_NONE) {
  879. WOLFSSL_MSG("Error loading config file into netRandom context");
  880. wnr_destroy(wnr_ctx);
  881. wnr_ctx = NULL;
  882. return RNG_FAILURE_E;
  883. }
  884. /* create/init polling mechanism */
  885. if (wnr_poll_create() != WNR_ERROR_NONE) {
  886. printf("ERROR: wnr_poll_create() failed\n");
  887. WOLFSSL_MSG("Error initializing netRandom polling mechanism");
  888. wnr_destroy(wnr_ctx);
  889. wnr_ctx = NULL;
  890. return RNG_FAILURE_E;
  891. }
  892. /* validate config, set HMAC callback (optional) */
  893. if (wnr_setup(wnr_ctx, hmac_cb) != WNR_ERROR_NONE) {
  894. WOLFSSL_MSG("Error setting up netRandom context");
  895. wnr_destroy(wnr_ctx);
  896. wnr_ctx = NULL;
  897. wnr_poll_destroy();
  898. return RNG_FAILURE_E;
  899. }
  900. wc_UnLockMutex(&wnr_mutex);
  901. return 0;
  902. }
  903. /*
  904. * Free global Whitewood netRandom context
  905. * Returns 0 on success, negative on error
  906. */
  907. int wc_FreeNetRandom(void)
  908. {
  909. if (wnr_mutex_init > 0) {
  910. if (wc_LockMutex(&wnr_mutex) != 0) {
  911. WOLFSSL_MSG("Bad Lock Mutex wnr_mutex");
  912. return BAD_MUTEX_E;
  913. }
  914. if (wnr_ctx != NULL) {
  915. wnr_destroy(wnr_ctx);
  916. wnr_ctx = NULL;
  917. }
  918. wnr_poll_destroy();
  919. wc_UnLockMutex(&wnr_mutex);
  920. wc_FreeMutex(&wnr_mutex);
  921. wnr_mutex_init = 0;
  922. }
  923. return 0;
  924. }
  925. #endif /* HAVE_WNR */
  926. #if defined(HAVE_INTEL_RDRAND) || defined(HAVE_INTEL_RDSEED)
  927. #ifdef WOLFSSL_ASYNC_CRYPT
  928. /* need more retries if multiple cores */
  929. #define INTELRD_RETRY (32 * 8)
  930. #else
  931. #define INTELRD_RETRY 32
  932. #endif
  933. #ifdef HAVE_INTEL_RDSEED
  934. #ifndef USE_WINDOWS_API
  935. /* return 0 on success */
  936. static WC_INLINE int IntelRDseed64(word64* seed)
  937. {
  938. unsigned char ok;
  939. __asm__ volatile("rdseed %0; setc %1":"=r"(*seed), "=qm"(ok));
  940. return (ok) ? 0 : -1;
  941. }
  942. #else /* USE_WINDOWS_API */
  943. /* The compiler Visual Studio uses does not allow inline assembly.
  944. * It does allow for Intel intrinsic functions. */
  945. /* return 0 on success */
  946. static WC_INLINE int IntelRDseed64(word64* seed)
  947. {
  948. int ok;
  949. ok = _rdseed64_step(seed);
  950. return (ok) ? 0 : -1;
  951. }
  952. #endif /* USE_WINDOWS_API */
  953. /* return 0 on success */
  954. static WC_INLINE int IntelRDseed64_r(word64* rnd)
  955. {
  956. int i;
  957. for (i = 0; i < INTELRD_RETRY; i++) {
  958. if (IntelRDseed64(rnd) == 0)
  959. return 0;
  960. }
  961. return -1;
  962. }
  963. /* return 0 on success */
  964. static int wc_GenerateSeed_IntelRD(OS_Seed* os, byte* output, word32 sz)
  965. {
  966. int ret;
  967. word64 rndTmp;
  968. (void)os;
  969. if (!IS_INTEL_RDSEED(intel_flags))
  970. return -1;
  971. for (; (sz / sizeof(word64)) > 0; sz -= sizeof(word64),
  972. output += sizeof(word64)) {
  973. ret = IntelRDseed64_r((word64*)output);
  974. if (ret != 0)
  975. return ret;
  976. }
  977. if (sz == 0)
  978. return 0;
  979. /* handle unaligned remainder */
  980. ret = IntelRDseed64_r(&rndTmp);
  981. if (ret != 0)
  982. return ret;
  983. XMEMCPY(output, &rndTmp, sz);
  984. ForceZero(&rndTmp, sizeof(rndTmp));
  985. return 0;
  986. }
  987. #endif /* HAVE_INTEL_RDSEED */
  988. #ifdef HAVE_INTEL_RDRAND
  989. #ifndef USE_WINDOWS_API
  990. /* return 0 on success */
  991. static WC_INLINE int IntelRDrand64(word64 *rnd)
  992. {
  993. unsigned char ok;
  994. __asm__ volatile("rdrand %0; setc %1":"=r"(*rnd), "=qm"(ok));
  995. return (ok) ? 0 : -1;
  996. }
  997. #else /* USE_WINDOWS_API */
  998. /* The compiler Visual Studio uses does not allow inline assembly.
  999. * It does allow for Intel intrinsic functions. */
  1000. /* return 0 on success */
  1001. static WC_INLINE int IntelRDrand64(word64 *rnd)
  1002. {
  1003. int ok;
  1004. ok = _rdrand64_step(rnd);
  1005. return (ok) ? 0 : -1;
  1006. }
  1007. #endif /* USE_WINDOWS_API */
  1008. /* return 0 on success */
  1009. static WC_INLINE int IntelRDrand64_r(word64 *rnd)
  1010. {
  1011. int i;
  1012. for (i = 0; i < INTELRD_RETRY; i++) {
  1013. if (IntelRDrand64(rnd) == 0)
  1014. return 0;
  1015. }
  1016. return -1;
  1017. }
  1018. /* return 0 on success */
  1019. static int wc_GenerateRand_IntelRD(OS_Seed* os, byte* output, word32 sz)
  1020. {
  1021. int ret;
  1022. word64 rndTmp;
  1023. (void)os;
  1024. if (!IS_INTEL_RDRAND(intel_flags))
  1025. return -1;
  1026. for (; (sz / sizeof(word64)) > 0; sz -= sizeof(word64),
  1027. output += sizeof(word64)) {
  1028. ret = IntelRDrand64_r((word64 *)output);
  1029. if (ret != 0)
  1030. return ret;
  1031. }
  1032. if (sz == 0)
  1033. return 0;
  1034. /* handle unaligned remainder */
  1035. ret = IntelRDrand64_r(&rndTmp);
  1036. if (ret != 0)
  1037. return ret;
  1038. XMEMCPY(output, &rndTmp, sz);
  1039. return 0;
  1040. }
  1041. #endif /* HAVE_INTEL_RDRAND */
  1042. #endif /* HAVE_INTEL_RDRAND || HAVE_INTEL_RDSEED */
  1043. /* Begin wc_GenerateSeed Implementations */
  1044. #if defined(CUSTOM_RAND_GENERATE_SEED)
  1045. /* Implement your own random generation function
  1046. * Return 0 to indicate success
  1047. * int rand_gen_seed(byte* output, word32 sz);
  1048. * #define CUSTOM_RAND_GENERATE_SEED rand_gen_seed */
  1049. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1050. {
  1051. (void)os; /* Suppress unused arg warning */
  1052. return CUSTOM_RAND_GENERATE_SEED(output, sz);
  1053. }
  1054. #elif defined(CUSTOM_RAND_GENERATE_SEED_OS)
  1055. /* Implement your own random generation function,
  1056. * which includes OS_Seed.
  1057. * Return 0 to indicate success
  1058. * int rand_gen_seed(OS_Seed* os, byte* output, word32 sz);
  1059. * #define CUSTOM_RAND_GENERATE_SEED_OS rand_gen_seed */
  1060. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1061. {
  1062. return CUSTOM_RAND_GENERATE_SEED_OS(os, output, sz);
  1063. }
  1064. #elif defined(CUSTOM_RAND_GENERATE)
  1065. /* Implement your own random generation function
  1066. * word32 rand_gen(void);
  1067. * #define CUSTOM_RAND_GENERATE rand_gen */
  1068. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1069. {
  1070. word32 i = 0;
  1071. (void)os;
  1072. while (i < sz)
  1073. {
  1074. /* If not aligned or there is odd/remainder */
  1075. if( (i + sizeof(CUSTOM_RAND_TYPE)) > sz ||
  1076. ((wolfssl_word)&output[i] % sizeof(CUSTOM_RAND_TYPE)) != 0
  1077. ) {
  1078. /* Single byte at a time */
  1079. output[i++] = (byte)CUSTOM_RAND_GENERATE();
  1080. }
  1081. else {
  1082. /* Use native 8, 16, 32 or 64 copy instruction */
  1083. *((CUSTOM_RAND_TYPE*)&output[i]) = CUSTOM_RAND_GENERATE();
  1084. i += sizeof(CUSTOM_RAND_TYPE);
  1085. }
  1086. }
  1087. return 0;
  1088. }
  1089. #elif defined(WOLFSSL_SGX)
  1090. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1091. {
  1092. int ret = !SGX_SUCCESS;
  1093. int i, read_max = 10;
  1094. for (i = 0; i < read_max && ret != SGX_SUCCESS; i++) {
  1095. ret = sgx_read_rand(output, sz);
  1096. }
  1097. (void)os;
  1098. return (ret == SGX_SUCCESS) ? 0 : 1;
  1099. }
  1100. #elif defined(USE_WINDOWS_API)
  1101. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1102. {
  1103. if(!CryptAcquireContext(&os->handle, 0, 0, PROV_RSA_FULL,
  1104. CRYPT_VERIFYCONTEXT))
  1105. return WINCRYPT_E;
  1106. if (!CryptGenRandom(os->handle, sz, output))
  1107. return CRYPTGEN_E;
  1108. CryptReleaseContext(os->handle, 0);
  1109. return 0;
  1110. }
  1111. #elif defined(HAVE_RTP_SYS) || defined(EBSNET)
  1112. #include "rtprand.h" /* rtp_rand () */
  1113. #include "rtptime.h" /* rtp_get_system_msec() */
  1114. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1115. {
  1116. int i;
  1117. rtp_srand(rtp_get_system_msec());
  1118. for (i = 0; i < sz; i++ ) {
  1119. output[i] = rtp_rand() % 256;
  1120. if ( (i % 8) == 7)
  1121. rtp_srand(rtp_get_system_msec());
  1122. }
  1123. return 0;
  1124. }
  1125. #elif defined(MICROCHIP_PIC32)
  1126. #ifdef MICROCHIP_MPLAB_HARMONY
  1127. #define PIC32_SEED_COUNT _CP0_GET_COUNT
  1128. #else
  1129. #if !defined(WOLFSSL_MICROCHIP_PIC32MZ)
  1130. #include <peripheral/timer.h>
  1131. #endif
  1132. extern word32 ReadCoreTimer(void);
  1133. #define PIC32_SEED_COUNT ReadCoreTimer
  1134. #endif
  1135. #ifdef WOLFSSL_PIC32MZ_RNG
  1136. #include "xc.h"
  1137. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1138. {
  1139. int i;
  1140. byte rnd[8];
  1141. word32 *rnd32 = (word32 *)rnd;
  1142. word32 size = sz;
  1143. byte* op = output;
  1144. #if ((__PIC32_FEATURE_SET0 == 'E') && (__PIC32_FEATURE_SET1 == 'C'))
  1145. RNGNUMGEN1 = _CP0_GET_COUNT();
  1146. RNGPOLY1 = _CP0_GET_COUNT();
  1147. RNGPOLY2 = _CP0_GET_COUNT();
  1148. RNGNUMGEN2 = _CP0_GET_COUNT();
  1149. #else
  1150. // All others can be seeded from the TRNG
  1151. RNGCONbits.TRNGMODE = 1;
  1152. RNGCONbits.TRNGEN = 1;
  1153. while (RNGCNT < 64);
  1154. RNGCONbits.LOAD = 1;
  1155. while (RNGCONbits.LOAD == 1);
  1156. while (RNGCNT < 64);
  1157. RNGPOLY2 = RNGSEED2;
  1158. RNGPOLY1 = RNGSEED1;
  1159. #endif
  1160. RNGCONbits.PLEN = 0x40;
  1161. RNGCONbits.PRNGEN = 1;
  1162. for (i=0; i<5; i++) { /* wait for RNGNUMGEN ready */
  1163. volatile int x;
  1164. x = RNGNUMGEN1;
  1165. x = RNGNUMGEN2;
  1166. (void)x;
  1167. }
  1168. do {
  1169. rnd32[0] = RNGNUMGEN1;
  1170. rnd32[1] = RNGNUMGEN2;
  1171. for(i=0; i<8; i++, op++) {
  1172. *op = rnd[i];
  1173. size --;
  1174. if(size==0)break;
  1175. }
  1176. } while(size);
  1177. return 0;
  1178. }
  1179. #else /* WOLFSSL_PIC32MZ_RNG */
  1180. /* uses the core timer, in nanoseconds to seed srand */
  1181. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1182. {
  1183. int i;
  1184. srand(PIC32_SEED_COUNT() * 25);
  1185. for (i = 0; i < sz; i++ ) {
  1186. output[i] = rand() % 256;
  1187. if ( (i % 8) == 7)
  1188. srand(PIC32_SEED_COUNT() * 25);
  1189. }
  1190. return 0;
  1191. }
  1192. #endif /* WOLFSSL_PIC32MZ_RNG */
  1193. #elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX) || \
  1194. defined(FREESCALE_KSDK_BM) || defined(FREESCALE_FREE_RTOS)
  1195. #if defined(FREESCALE_K70_RNGA) || defined(FREESCALE_RNGA)
  1196. /*
  1197. * wc_Generates a RNG seed using the Random Number Generator Accelerator
  1198. * on the Kinetis K70. Documentation located in Chapter 37 of
  1199. * K70 Sub-Family Reference Manual (see Note 3 in the README for link).
  1200. */
  1201. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1202. {
  1203. word32 i;
  1204. /* turn on RNGA module */
  1205. #if defined(SIM_SCGC3_RNGA_MASK)
  1206. SIM_SCGC3 |= SIM_SCGC3_RNGA_MASK;
  1207. #endif
  1208. #if defined(SIM_SCGC6_RNGA_MASK)
  1209. /* additionally needed for at least K64F */
  1210. SIM_SCGC6 |= SIM_SCGC6_RNGA_MASK;
  1211. #endif
  1212. /* set SLP bit to 0 - "RNGA is not in sleep mode" */
  1213. RNG_CR &= ~RNG_CR_SLP_MASK;
  1214. /* set HA bit to 1 - "security violations masked" */
  1215. RNG_CR |= RNG_CR_HA_MASK;
  1216. /* set GO bit to 1 - "output register loaded with data" */
  1217. RNG_CR |= RNG_CR_GO_MASK;
  1218. for (i = 0; i < sz; i++) {
  1219. /* wait for RNG FIFO to be full */
  1220. while((RNG_SR & RNG_SR_OREG_LVL(0xF)) == 0) {}
  1221. /* get value */
  1222. output[i] = RNG_OR;
  1223. }
  1224. return 0;
  1225. }
  1226. #elif defined(FREESCALE_K53_RNGB) || defined(FREESCALE_RNGB)
  1227. /*
  1228. * wc_Generates a RNG seed using the Random Number Generator (RNGB)
  1229. * on the Kinetis K53. Documentation located in Chapter 33 of
  1230. * K53 Sub-Family Reference Manual (see note in the README for link).
  1231. */
  1232. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1233. {
  1234. int i;
  1235. /* turn on RNGB module */
  1236. SIM_SCGC3 |= SIM_SCGC3_RNGB_MASK;
  1237. /* reset RNGB */
  1238. RNG_CMD |= RNG_CMD_SR_MASK;
  1239. /* FIFO generate interrupt, return all zeros on underflow,
  1240. * set auto reseed */
  1241. RNG_CR |= (RNG_CR_FUFMOD_MASK | RNG_CR_AR_MASK);
  1242. /* gen seed, clear interrupts, clear errors */
  1243. RNG_CMD |= (RNG_CMD_GS_MASK | RNG_CMD_CI_MASK | RNG_CMD_CE_MASK);
  1244. /* wait for seeding to complete */
  1245. while ((RNG_SR & RNG_SR_SDN_MASK) == 0) {}
  1246. for (i = 0; i < sz; i++) {
  1247. /* wait for a word to be available from FIFO */
  1248. while((RNG_SR & RNG_SR_FIFO_LVL_MASK) == 0) {}
  1249. /* get value */
  1250. output[i] = RNG_OUT;
  1251. }
  1252. return 0;
  1253. }
  1254. #elif defined(FREESCALE_KSDK_2_0_TRNG)
  1255. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1256. {
  1257. status_t status;
  1258. status = TRNG_GetRandomData(TRNG0, output, sz);
  1259. if (status == kStatus_Success)
  1260. {
  1261. return(0);
  1262. }
  1263. else
  1264. {
  1265. return RAN_BLOCK_E;
  1266. }
  1267. }
  1268. #elif defined(FREESCALE_KSDK_2_0_RNGA)
  1269. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1270. {
  1271. status_t status;
  1272. status = RNGA_GetRandomData(RNG, output, sz);
  1273. if (status == kStatus_Success)
  1274. {
  1275. return(0);
  1276. }
  1277. else
  1278. {
  1279. return RAN_BLOCK_E;
  1280. }
  1281. }
  1282. #elif defined(FREESCALE_RNGA)
  1283. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1284. {
  1285. RNGA_DRV_GetRandomData(RNGA_INSTANCE, output, sz);
  1286. return 0;
  1287. }
  1288. #else
  1289. #define USE_TEST_GENSEED
  1290. #endif /* FREESCALE_K70_RNGA */
  1291. #elif defined(STM32_RNG)
  1292. /* Generate a RNG seed using the hardware random number generator
  1293. * on the STM32F2/F4/F7. */
  1294. #ifdef WOLFSSL_STM32_CUBEMX
  1295. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1296. {
  1297. RNG_HandleTypeDef hrng;
  1298. int i;
  1299. (void)os;
  1300. /* enable RNG clock source */
  1301. __HAL_RCC_RNG_CLK_ENABLE();
  1302. /* enable RNG peripheral */
  1303. hrng.Instance = RNG;
  1304. HAL_RNG_Init(&hrng);
  1305. for (i = 0; i < (int)sz; i++) {
  1306. /* get value */
  1307. output[i] = (byte)HAL_RNG_GetRandomNumber(&hrng);
  1308. }
  1309. return 0;
  1310. }
  1311. #elif defined(WOLFSSL_STM32F427_RNG)
  1312. /* Generate a RNG seed using the hardware RNG on the STM32F427
  1313. * directly, following steps outlined in STM32F4 Reference
  1314. * Manual (Chapter 24) for STM32F4xx family. */
  1315. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1316. {
  1317. int i;
  1318. (void)os;
  1319. /* enable RNG interrupt, set IE bit in RNG->CR register */
  1320. RNG->CR |= RNG_CR_IE;
  1321. /* enable RNG, set RNGEN bit in RNG->CR. Activates RNG,
  1322. * RNG_LFSR, and error detector */
  1323. RNG->CR |= RNG_CR_RNGEN;
  1324. /* verify no errors, make sure SEIS and CEIS bits are 0
  1325. * in RNG->SR register */
  1326. if (RNG->SR & (RNG_SR_SECS | RNG_SR_CECS))
  1327. return RNG_FAILURE_E;
  1328. for (i = 0; i < (int)sz; i++) {
  1329. /* wait until RNG number is ready */
  1330. while ((RNG->SR & RNG_SR_DRDY) == 0) { }
  1331. /* get value */
  1332. output[i] = RNG->DR;
  1333. }
  1334. return 0;
  1335. }
  1336. #else
  1337. /* Generate a RNG seed using the STM32 Standard Peripheral Library */
  1338. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1339. {
  1340. int i;
  1341. (void)os;
  1342. /* enable RNG clock source */
  1343. RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_RNG, ENABLE);
  1344. /* reset RNG */
  1345. RNG_DeInit();
  1346. /* enable RNG peripheral */
  1347. RNG_Cmd(ENABLE);
  1348. /* verify no errors with RNG_CLK or Seed */
  1349. if (RNG_GetFlagStatus(RNG_FLAG_SECS | RNG_FLAG_CECS) != RESET)
  1350. return RNG_FAILURE_E;
  1351. for (i = 0; i < (int)sz; i++) {
  1352. /* wait until RNG number is ready */
  1353. while (RNG_GetFlagStatus(RNG_FLAG_DRDY) == RESET) { }
  1354. /* get value */
  1355. output[i] = RNG_GetRandomNumber();
  1356. }
  1357. return 0;
  1358. }
  1359. #endif /* WOLFSSL_STM32_CUBEMX */
  1360. #elif defined(WOLFSSL_TIRTOS)
  1361. #include <xdc/runtime/Timestamp.h>
  1362. #include <stdlib.h>
  1363. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1364. {
  1365. int i;
  1366. srand(xdc_runtime_Timestamp_get32());
  1367. for (i = 0; i < sz; i++ ) {
  1368. output[i] = rand() % 256;
  1369. if ((i % 8) == 7) {
  1370. srand(xdc_runtime_Timestamp_get32());
  1371. }
  1372. }
  1373. return 0;
  1374. }
  1375. #elif defined(WOLFSSL_PB)
  1376. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1377. {
  1378. word32 i;
  1379. for (i = 0; i < sz; i++)
  1380. output[i] = UTL_Rand();
  1381. (void)os;
  1382. return 0;
  1383. }
  1384. #elif defined(WOLFSSL_NUCLEUS)
  1385. #include "nucleus.h"
  1386. #include "kernel/plus_common.h"
  1387. #warning "potential for not enough entropy, currently being used for testing"
  1388. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1389. {
  1390. int i;
  1391. srand(NU_Get_Time_Stamp());
  1392. for (i = 0; i < sz; i++ ) {
  1393. output[i] = rand() % 256;
  1394. if ((i % 8) == 7) {
  1395. srand(NU_Get_Time_Stamp());
  1396. }
  1397. }
  1398. return 0;
  1399. }
  1400. #elif defined(WOLFSSL_VXWORKS)
  1401. #include <randomNumGen.h>
  1402. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) {
  1403. STATUS status;
  1404. #ifdef VXWORKS_SIM
  1405. /* cannot generate true entropy with VxWorks simulator */
  1406. #warning "not enough entropy, simulator for testing only"
  1407. int i = 0;
  1408. for (i = 0; i < 1000; i++) {
  1409. randomAddTimeStamp();
  1410. }
  1411. #endif
  1412. status = randBytes (output, sz);
  1413. if (status == ERROR) {
  1414. return RNG_FAILURE_E;
  1415. }
  1416. return 0;
  1417. }
  1418. #elif defined(WOLFSSL_NRF51)
  1419. #include "app_error.h"
  1420. #include "nrf_drv_rng.h"
  1421. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1422. {
  1423. int remaining = sz, length, pos = 0;
  1424. uint8_t available;
  1425. uint32_t err_code;
  1426. (void)os;
  1427. /* Make sure RNG is running */
  1428. err_code = nrf_drv_rng_init(NULL);
  1429. if (err_code != NRF_SUCCESS && err_code != NRF_ERROR_INVALID_STATE) {
  1430. return -1;
  1431. }
  1432. while (remaining > 0) {
  1433. err_code = nrf_drv_rng_bytes_available(&available);
  1434. if (err_code == NRF_SUCCESS) {
  1435. length = (remaining < available) ? remaining : available;
  1436. if (length > 0) {
  1437. err_code = nrf_drv_rng_rand(&output[pos], length);
  1438. remaining -= length;
  1439. pos += length;
  1440. }
  1441. }
  1442. if (err_code != NRF_SUCCESS) {
  1443. break;
  1444. }
  1445. }
  1446. return (err_code == NRF_SUCCESS) ? 0 : -1;
  1447. }
  1448. #elif defined(HAVE_WNR)
  1449. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1450. {
  1451. if (os == NULL || output == NULL || wnr_ctx == NULL ||
  1452. wnr_timeout < 0) {
  1453. return BAD_FUNC_ARG;
  1454. }
  1455. if (wnr_mutex_init == 0) {
  1456. WOLFSSL_MSG("netRandom context must be created before use");
  1457. return RNG_FAILURE_E;
  1458. }
  1459. if (wc_LockMutex(&wnr_mutex) != 0) {
  1460. WOLFSSL_MSG("Bad Lock Mutex wnr_mutex\n");
  1461. return BAD_MUTEX_E;
  1462. }
  1463. if (wnr_get_entropy(wnr_ctx, wnr_timeout, output, sz, sz) !=
  1464. WNR_ERROR_NONE)
  1465. return RNG_FAILURE_E;
  1466. wc_UnLockMutex(&wnr_mutex);
  1467. return 0;
  1468. }
  1469. #elif defined(WOLFSSL_ATMEL)
  1470. #include <wolfssl/wolfcrypt/port/atmel/atmel.h>
  1471. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1472. {
  1473. int ret = 0;
  1474. (void)os;
  1475. if (output == NULL) {
  1476. return BUFFER_E;
  1477. }
  1478. ret = atmel_get_random_number(sz, output);
  1479. return ret;
  1480. }
  1481. #elif defined(INTIME_RTOS)
  1482. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1483. {
  1484. int ret = 0;
  1485. (void)os;
  1486. if (output == NULL) {
  1487. return BUFFER_E;
  1488. }
  1489. /* Note: Investigate better solution */
  1490. /* no return to check */
  1491. arc4random_buf(output, sz);
  1492. return ret;
  1493. }
  1494. #elif defined(IDIRECT_DEV_RANDOM)
  1495. extern int getRandom( int sz, unsigned char *output );
  1496. int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1497. {
  1498. int num_bytes_returned = 0;
  1499. num_bytes_returned = getRandom( (int) sz, (unsigned char *) output );
  1500. return 0;
  1501. }
  1502. #elif (defined(WOLFSSL_IMX6_CAAM) || defined(WOLFSSL_IMX6_CAAM_RNG))
  1503. #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h>
  1504. #include <wolfssl/wolfcrypt/port/caam/caam_driver.h>
  1505. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1506. {
  1507. Buffer buf[1];
  1508. int ret = 0;
  1509. int times = 1000, i;
  1510. (void)os;
  1511. if (output == NULL) {
  1512. return BUFFER_E;
  1513. }
  1514. buf[0].BufferType = DataBuffer | LastBuffer;
  1515. buf[0].TheAddress = (Address)output;
  1516. buf[0].Length = sz;
  1517. /* Check Waiting to make sure entropy is ready */
  1518. for (i = 0; i < times; i++) {
  1519. ret = wc_caamAddAndWait(buf, NULL, CAAM_ENTROPY);
  1520. if (ret == Success) {
  1521. break;
  1522. }
  1523. /* driver could be waiting for entropy */
  1524. if (ret != RAN_BLOCK_E) {
  1525. return ret;
  1526. }
  1527. usleep(100);
  1528. }
  1529. if (i == times && ret != Success) {
  1530. return RNG_FAILURE_E;
  1531. }
  1532. else { /* Success case */
  1533. ret = 0;
  1534. }
  1535. return ret;
  1536. }
  1537. #elif defined(WOLFSSL_APACHE_MYNEWT)
  1538. #include <stdlib.h>
  1539. #include "os/os_time.h"
  1540. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1541. {
  1542. int i;
  1543. srand(os_time_get());
  1544. for (i = 0; i < sz; i++ ) {
  1545. output[i] = rand() % 256;
  1546. if ((i % 8) == 7) {
  1547. srand(os_time_get());
  1548. }
  1549. }
  1550. return 0;
  1551. }
  1552. #elif defined(CUSTOM_RAND_GENERATE_BLOCK)
  1553. /* #define CUSTOM_RAND_GENERATE_BLOCK myRngFunc
  1554. * extern int myRngFunc(byte* output, word32 sz);
  1555. */
  1556. #elif defined(WOLFSSL_SAFERTOS) || defined(WOLFSSL_LEANPSK) || \
  1557. defined(WOLFSSL_IAR_ARM) || defined(WOLFSSL_MDK_ARM) || \
  1558. defined(WOLFSSL_uITRON4) || defined(WOLFSSL_uTKERNEL2) || \
  1559. defined(WOLFSSL_LPC43xx) || defined(WOLFSSL_STM32F2xx) || \
  1560. defined(MBED) || defined(WOLFSSL_EMBOS) || \
  1561. defined(WOLFSSL_GENSEED_FORTEST) || defined(WOLFSSL_CHIBIOS)
  1562. /* these platforms do not have a default random seed and
  1563. you'll need to implement your own wc_GenerateSeed or define via
  1564. CUSTOM_RAND_GENERATE_BLOCK */
  1565. #define USE_TEST_GENSEED
  1566. #elif defined(NO_DEV_RANDOM)
  1567. #error "you need to write an os specific wc_GenerateSeed() here"
  1568. /*
  1569. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1570. {
  1571. return 0;
  1572. }
  1573. */
  1574. #else
  1575. /* may block */
  1576. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1577. {
  1578. int ret = 0;
  1579. #ifdef HAVE_INTEL_RDSEED
  1580. if (IS_INTEL_RDSEED(intel_flags)) {
  1581. ret = wc_GenerateSeed_IntelRD(NULL, output, sz);
  1582. if (ret == 0) {
  1583. /* success, we're done */
  1584. return ret;
  1585. }
  1586. #ifdef FORCE_FAILURE_RDSEED
  1587. /* don't fallback to /dev/urandom */
  1588. return ret;
  1589. #else
  1590. /* reset error and fallback to using /dev/urandom */
  1591. ret = 0;
  1592. #endif
  1593. }
  1594. #endif /* HAVE_INTEL_RDSEED */
  1595. #ifndef NO_DEV_URANDOM /* way to disable use of /dev/urandom */
  1596. os->fd = open("/dev/urandom", O_RDONLY);
  1597. if (os->fd == -1)
  1598. #endif
  1599. {
  1600. /* may still have /dev/random */
  1601. os->fd = open("/dev/random", O_RDONLY);
  1602. if (os->fd == -1)
  1603. return OPEN_RAN_E;
  1604. }
  1605. while (sz) {
  1606. int len = (int)read(os->fd, output, sz);
  1607. if (len == -1) {
  1608. ret = READ_RAN_E;
  1609. break;
  1610. }
  1611. sz -= len;
  1612. output += len;
  1613. if (sz) {
  1614. #if defined(BLOCKING) || defined(WC_RNG_BLOCKING)
  1615. sleep(0); /* context switch */
  1616. #else
  1617. ret = RAN_BLOCK_E;
  1618. break;
  1619. #endif
  1620. }
  1621. }
  1622. close(os->fd);
  1623. return ret;
  1624. }
  1625. #endif
  1626. #ifdef USE_TEST_GENSEED
  1627. #ifndef _MSC_VER
  1628. #warning "write a real random seed!!!!, just for testing now"
  1629. #else
  1630. #pragma message("Warning: write a real random seed!!!!, just for testing now")
  1631. #endif
  1632. int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
  1633. {
  1634. word32 i;
  1635. for (i = 0; i < sz; i++ )
  1636. output[i] = i;
  1637. (void)os;
  1638. return 0;
  1639. }
  1640. #endif
  1641. /* End wc_GenerateSeed */
  1642. #endif /* WC_NO_RNG */
  1643. #endif /* HAVE_FIPS */