3 * Copyright (C) 2006-2014 wolfSSL Inc.
5 * This file is part of CyaSSL.
7 * CyaSSL 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.
12 * CyaSSL 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.
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-1301, USA
26 #include <cyassl/ctaocrypt/settings.h>
28 /* on HPUX 11 you may need to install /dev/random see
29 http://h20293.www2.hp.com/portal/swdepot/displayProductInfo.do?productNumber=KRNG11I
34 /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */
35 #define FIPS_NO_WRAPPERS
38 #include <cyassl/ctaocrypt/random.h>
39 #include <cyassl/ctaocrypt/error-crypt.h>
41 #if defined(HAVE_HASHDRBG) || defined(NO_RC4)
43 #include <cyassl/ctaocrypt/sha256.h>
46 #include <cyassl/ctaocrypt/misc.h>
48 #include <ctaocrypt/src/misc.c>
50 #endif /* HAVE_HASHDRBG || NO_RC4 */
52 #if defined(USE_WINDOWS_API)
54 #define _WIN32_WINNT 0x0400
59 #if !defined(NO_DEV_RANDOM) && !defined(CYASSL_MDK_ARM) \
60 && !defined(CYASSL_IAR_ARM)
66 /* include headers that may be needed to get good seed */
68 #endif /* USE_WINDOWS_API */
71 #if defined(HAVE_HASHDRBG) || defined(NO_RC4)
73 /* Start NIST DRBG code */
75 #define OUTPUT_BLOCK_LEN (SHA256_DIGEST_SIZE)
76 #define MAX_REQUEST_LEN (0x10000)
77 #define RESEED_INTERVAL (1000000)
78 #define SECURITY_STRENGTH (256)
79 #define ENTROPY_SZ (SECURITY_STRENGTH/8)
80 #define NONCE_SZ (ENTROPY_SZ/2)
81 #define ENTROPY_NONCE_SZ (ENTROPY_SZ+NONCE_SZ)
83 /* Internal return codes */
84 #define DRBG_SUCCESS 0
86 #define DRBG_FAILURE 2
87 #define DRBG_NEED_RESEED 3
89 /* RNG health states */
90 #define DRBG_NOT_INIT 0
104 /* Hash Derivation Function */
105 /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
106 static int Hash_df(RNG* rng, byte* out, word32 outSz, byte type,
107 const byte* inA, word32 inASz,
108 const byte* inB, word32 inBSz)
113 word32 bits = (outSz * 8); /* reverse byte order */
115 #ifdef LITTLE_ENDIAN_ORDER
116 bits = ByteReverseWord32(bits);
118 len = (outSz / OUTPUT_BLOCK_LEN)
119 + ((outSz % OUTPUT_BLOCK_LEN) ? 1 : 0);
121 for (i = 0, ctr = 1; i < len; i++, ctr++)
123 if (InitSha256(&rng->sha) != 0)
126 if (Sha256Update(&rng->sha, &ctr, sizeof(ctr)) != 0)
129 if (Sha256Update(&rng->sha, (byte*)&bits, sizeof(bits)) != 0)
132 /* churning V is the only string that doesn't have
134 if (type != drbgInitV)
135 if (Sha256Update(&rng->sha, &type, sizeof(type)) != 0)
138 if (Sha256Update(&rng->sha, inA, inASz) != 0)
141 if (inB != NULL && inBSz > 0)
142 if (Sha256Update(&rng->sha, inB, inBSz) != 0)
145 if (Sha256Final(&rng->sha, rng->digest) != 0)
148 if (outSz > OUTPUT_BLOCK_LEN) {
149 XMEMCPY(out, rng->digest, OUTPUT_BLOCK_LEN);
150 outSz -= OUTPUT_BLOCK_LEN;
151 out += OUTPUT_BLOCK_LEN;
154 XMEMCPY(out, rng->digest, outSz);
162 /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
163 static int Hash_DRBG_Reseed(RNG* rng, const byte* entropy, word32 entropySz)
165 byte seed[DRBG_SEED_LEN];
167 if (Hash_df(rng, seed, sizeof(seed), drbgReseed, rng->V, sizeof(rng->V),
168 entropy, entropySz) != DRBG_SUCCESS) {
172 XMEMCPY(rng->V, seed, sizeof(rng->V));
173 XMEMSET(seed, 0, sizeof(seed));
175 if (Hash_df(rng, rng->C, sizeof(rng->C), drbgInitC, rng->V,
176 sizeof(rng->V), NULL, 0) != DRBG_SUCCESS) {
184 static INLINE void array_add_one(byte* data, word32 dataSz)
188 for (i = dataSz - 1; i >= 0; i--)
191 if (data[i] != 0) break;
196 /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
197 static int Hash_gen(RNG* rng, byte* out, word32 outSz, const byte* V)
199 byte data[DRBG_SEED_LEN];
201 int len = (outSz / OUTPUT_BLOCK_LEN)
202 + ((outSz % OUTPUT_BLOCK_LEN) ? 1 : 0);
204 XMEMCPY(data, V, sizeof(data));
205 for (i = 0; i < len; i++) {
206 if (InitSha256(&rng->sha) != 0 ||
207 Sha256Update(&rng->sha, data, sizeof(data)) != 0 ||
208 Sha256Final(&rng->sha, rng->digest) != 0) {
213 if (outSz > OUTPUT_BLOCK_LEN) {
214 XMEMCPY(out, rng->digest, OUTPUT_BLOCK_LEN);
215 outSz -= OUTPUT_BLOCK_LEN;
216 out += OUTPUT_BLOCK_LEN;
217 array_add_one(data, DRBG_SEED_LEN);
220 XMEMCPY(out, rng->digest, outSz);
223 XMEMSET(data, 0, sizeof(data));
229 static INLINE void array_add(byte* d, word32 dLen, const byte* s, word32 sLen)
233 if (dLen > 0 && sLen > 0 && dLen >= sLen) {
236 for (sIdx = sLen - 1, dIdx = dLen - 1; sIdx >= 0; dIdx--, sIdx--)
238 carry += d[dIdx] + s[sIdx];
248 /* Returns: DRBG_SUCCESS, DRBG_NEED_RESEED, or DRBG_FAILURE */
249 static int Hash_DRBG_Generate(RNG* rng, byte* out, word32 outSz)
251 int ret = DRBG_NEED_RESEED;
253 if (rng->reseedCtr != RESEED_INTERVAL) {
254 byte type = drbgGenerateH;
255 word32 reseedCtr = rng->reseedCtr;
258 if (Hash_gen(rng, out, outSz, rng->V) != 0 ||
259 InitSha256(&rng->sha) != 0 ||
260 Sha256Update(&rng->sha, &type, sizeof(type)) != 0 ||
261 Sha256Update(&rng->sha, rng->V, sizeof(rng->V)) != 0 ||
262 Sha256Final(&rng->sha, rng->digest) != 0) {
267 array_add(rng->V, sizeof(rng->V), rng->digest, sizeof(rng->digest));
268 array_add(rng->V, sizeof(rng->V), rng->C, sizeof(rng->C));
269 #ifdef LITTLE_ENDIAN_ORDER
270 reseedCtr = ByteReverseWord32(reseedCtr);
272 array_add(rng->V, sizeof(rng->V),
273 (byte*)&reseedCtr, sizeof(reseedCtr));
282 /* Returns: DRBG_SUCCESS or DRBG_FAILURE */
283 static int Hash_DRBG_Instantiate(RNG* rng, const byte* seed, word32 seedSz,
284 const byte* nonce, word32 nonceSz)
286 int ret = DRBG_FAILURE;
288 XMEMSET(rng, 0, sizeof(*rng));
290 if (Hash_df(rng, rng->V, sizeof(rng->V), drbgInitV, seed, seedSz,
291 nonce, nonceSz) == DRBG_SUCCESS &&
292 Hash_df(rng, rng->C, sizeof(rng->C), drbgInitC, rng->V,
293 sizeof(rng->V), NULL, 0) == DRBG_SUCCESS) {
303 /* Returns: DRBG_SUCCESS */
304 static int Hash_DRBG_Uninstantiate(RNG* rng)
306 XMEMSET(rng, 0, sizeof(*rng));
311 /* End NIST DRBG Code */
314 /* Get seed and key cipher */
315 int InitRng(RNG* rng)
317 int ret = BAD_FUNC_ARG;
320 byte entropy[ENTROPY_NONCE_SZ];
322 /* This doesn't use a separate nonce. The entropy input will be
323 * the default size plus the size of the nonce making the seed
325 if (GenerateSeed(&rng->seed, entropy, ENTROPY_NONCE_SZ) == 0 &&
326 Hash_DRBG_Instantiate(rng, entropy, ENTROPY_NONCE_SZ,
327 NULL, 0) == DRBG_SUCCESS) {
328 rng->status = DRBG_OK;
332 rng->status = DRBG_FAILED;
336 XMEMSET(entropy, 0, ENTROPY_NONCE_SZ);
343 /* place a generated block in output */
344 int RNG_GenerateBlock(RNG* rng, byte* output, word32 sz)
348 if (rng == NULL || output == NULL || sz > MAX_REQUEST_LEN)
351 if (rng->status != DRBG_OK)
352 return RNG_FAILURE_E;
354 ret = Hash_DRBG_Generate(rng, output, sz);
355 if (ret == DRBG_SUCCESS) {
358 else if (ret == DRBG_NEED_RESEED) {
359 byte entropy[ENTROPY_SZ];
361 if (GenerateSeed(&rng->seed, entropy, ENTROPY_SZ) == 0 &&
362 Hash_DRBG_Reseed(rng, entropy, ENTROPY_SZ) == DRBG_SUCCESS &&
363 Hash_DRBG_Generate(rng, output, sz) == DRBG_SUCCESS) {
369 rng->status = DRBG_FAILED;
372 XMEMSET(entropy, 0, ENTROPY_SZ);
376 rng->status = DRBG_FAILED;
383 int RNG_GenerateByte(RNG* rng, byte* b)
385 return RNG_GenerateBlock(rng, b, 1);
389 int FreeRng(RNG* rng)
391 int ret = BAD_FUNC_ARG;
394 if (Hash_DRBG_Uninstantiate(rng) == DRBG_SUCCESS)
404 int RNG_HealthTest(int reseed, const byte* entropyA, word32 entropyASz,
405 const byte* entropyB, word32 entropyBSz,
406 const byte* output, word32 outputSz)
409 byte check[SHA256_DIGEST_SIZE * 4];
411 if (Hash_DRBG_Instantiate(&rng, entropyA, entropyASz, NULL, 0) != 0)
415 if (Hash_DRBG_Reseed(&rng, entropyB, entropyBSz) != 0) {
416 Hash_DRBG_Uninstantiate(&rng);
421 if (Hash_DRBG_Generate(&rng, check, sizeof(check)) != 0) {
422 Hash_DRBG_Uninstantiate(&rng);
426 if (Hash_DRBG_Generate(&rng, check, sizeof(check)) != 0) {
427 Hash_DRBG_Uninstantiate(&rng);
431 if (outputSz != sizeof(check) || XMEMCMP(output, check, sizeof(check))) {
432 Hash_DRBG_Uninstantiate(&rng);
436 Hash_DRBG_Uninstantiate(&rng);
442 #else /* HAVE_HASHDRBG || NO_RC4 */
444 /* Get seed and key cipher */
445 int InitRng(RNG* rng)
448 #ifdef CYASSL_SMALL_STACK
457 if (rng->magic == CYASSL_RNG_CAVIUM_MAGIC)
461 #ifdef CYASSL_SMALL_STACK
462 key = (byte*)XMALLOC(32, NULL, DYNAMIC_TYPE_TMP_BUFFER);
466 junk = (byte*)XMALLOC(256, NULL, DYNAMIC_TYPE_TMP_BUFFER);
468 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
473 ret = GenerateSeed(&rng->seed, key, 32);
476 Arc4SetKey(&rng->cipher, key, sizeof(key));
478 ret = RNG_GenerateBlock(rng, junk, 256); /*rid initial state*/
481 #ifdef CYASSL_SMALL_STACK
482 XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
483 XFREE(junk, NULL, DYNAMIC_TYPE_TMP_BUFFER);
490 static void CaviumRNG_GenerateBlock(RNG* rng, byte* output, word32 sz);
493 /* place a generated block in output */
494 int RNG_GenerateBlock(RNG* rng, byte* output, word32 sz)
497 if (rng->magic == CYASSL_RNG_CAVIUM_MAGIC)
498 return CaviumRNG_GenerateBlock(rng, output, sz);
500 XMEMSET(output, 0, sz);
501 Arc4Process(&rng->cipher, output, output, sz);
507 int RNG_GenerateByte(RNG* rng, byte* b)
509 return RNG_GenerateBlock(rng, b, 1);
515 #include <cyassl/ctaocrypt/logging.h>
516 #include "cavium_common.h"
518 /* Initiliaze RNG for use with Nitrox device */
519 int InitRngCavium(RNG* rng, int devId)
525 rng->magic = CYASSL_RNG_CAVIUM_MAGIC;
531 static void CaviumRNG_GenerateBlock(RNG* rng, byte* output, word32 sz)
536 while (sz > CYASSL_MAX_16BIT) {
537 word16 slen = (word16)CYASSL_MAX_16BIT;
538 if (CspRandom(CAVIUM_BLOCKING, slen, output + offset, &requestId,
540 CYASSL_MSG("Cavium RNG failed");
542 sz -= CYASSL_MAX_16BIT;
543 offset += CYASSL_MAX_16BIT;
546 word16 slen = (word16)sz;
547 if (CspRandom(CAVIUM_BLOCKING, slen, output + offset, &requestId,
549 CYASSL_MSG("Cavium RNG failed");
554 #endif /* HAVE_CAVIUM */
556 #endif /* HAVE_HASHDRBG || NO_RC4 */
559 #if defined(USE_WINDOWS_API)
562 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
564 if(!CryptAcquireContext(&os->handle, 0, 0, PROV_RSA_FULL,
565 CRYPT_VERIFYCONTEXT))
568 if (!CryptGenRandom(os->handle, sz, output))
571 CryptReleaseContext(os->handle, 0);
577 #elif defined(HAVE_RTP_SYS) || defined(EBSNET)
579 #include "rtprand.h" /* rtp_rand () */
580 #include "rtptime.h" /* rtp_get_system_msec() */
583 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
586 rtp_srand(rtp_get_system_msec());
588 for (i = 0; i < sz; i++ ) {
589 output[i] = rtp_rand() % 256;
591 rtp_srand(rtp_get_system_msec());
598 #elif defined(MICRIUM)
600 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
602 #if (NET_SECURE_MGR_CFG_EN == DEF_ENABLED)
603 NetSecure_InitSeed(output, sz);
610 /* write a real one !!!, just for testing board */
611 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
614 for (i = 0; i < sz; i++ )
620 #elif defined(MICROCHIP_PIC32)
622 #ifdef MICROCHIP_MPLAB_HARMONY
623 #define PIC32_SEED_COUNT _CP0_GET_COUNT
625 #if !defined(CYASSL_MICROCHIP_PIC32MZ)
626 #include <peripheral/timer.h>
628 #define PIC32_SEED_COUNT ReadCoreTimer
630 #ifdef CYASSL_MIC32MZ_RNG
632 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
636 word32 *rnd32 = (word32 *)rnd ;
640 /* This part has to be replaced with better random seed */
641 RNGNUMGEN1 = ReadCoreTimer();
642 RNGPOLY1 = ReadCoreTimer();
643 RNGPOLY2 = ReadCoreTimer();
644 RNGNUMGEN2 = ReadCoreTimer();
646 printf("GenerateSeed::Seed=%08x, %08x\n", RNGNUMGEN1, RNGNUMGEN2) ;
648 RNGCONbits.PLEN = 0x40;
649 RNGCONbits.PRNGEN = 1;
650 for(i=0; i<5; i++) { /* wait for RNGNUMGEN ready */
656 rnd32[0] = RNGNUMGEN1;
657 rnd32[1] = RNGNUMGEN2;
659 for(i=0; i<8; i++, op++) {
667 #else /* CYASSL_MIC32MZ_RNG */
668 /* uses the core timer, in nanoseconds to seed srand */
669 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
672 srand(PIC32_SEED_COUNT() * 25);
674 for (i = 0; i < sz; i++ ) {
675 output[i] = rand() % 256;
677 srand(PIC32_SEED_COUNT() * 25);
681 #endif /* CYASSL_MIC32MZ_RNG */
683 #elif defined(FREESCALE_MQX)
685 #ifdef FREESCALE_K70_RNGA
687 * Generates a RNG seed using the Random Number Generator Accelerator
688 * on the Kinetis K70. Documentation located in Chapter 37 of
689 * K70 Sub-Family Reference Manual (see Note 3 in the README for link).
691 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
695 /* turn on RNGA module */
696 SIM_SCGC3 |= SIM_SCGC3_RNGA_MASK;
698 /* set SLP bit to 0 - "RNGA is not in sleep mode" */
699 RNG_CR &= ~RNG_CR_SLP_MASK;
701 /* set HA bit to 1 - "security violations masked" */
702 RNG_CR |= RNG_CR_HA_MASK;
704 /* set GO bit to 1 - "output register loaded with data" */
705 RNG_CR |= RNG_CR_GO_MASK;
707 for (i = 0; i < sz; i++) {
709 /* wait for RNG FIFO to be full */
710 while((RNG_SR & RNG_SR_OREG_LVL(0xF)) == 0) {}
719 #elif defined(FREESCALE_K53_RNGB)
721 * Generates a RNG seed using the Random Number Generator (RNGB)
722 * on the Kinetis K53. Documentation located in Chapter 33 of
723 * K53 Sub-Family Reference Manual (see note in the README for link).
725 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
729 /* turn on RNGB module */
730 SIM_SCGC3 |= SIM_SCGC3_RNGB_MASK;
733 RNG_CMD |= RNG_CMD_SR_MASK;
735 /* FIFO generate interrupt, return all zeros on underflow,
737 RNG_CR |= (RNG_CR_FUFMOD_MASK | RNG_CR_AR_MASK);
739 /* gen seed, clear interrupts, clear errors */
740 RNG_CMD |= (RNG_CMD_GS_MASK | RNG_CMD_CI_MASK | RNG_CMD_CE_MASK);
742 /* wait for seeding to complete */
743 while ((RNG_SR & RNG_SR_SDN_MASK) == 0) {}
745 for (i = 0; i < sz; i++) {
747 /* wait for a word to be available from FIFO */
748 while((RNG_SR & RNG_SR_FIFO_LVL_MASK) == 0) {}
758 #warning "write a real random seed!!!!, just for testing now"
760 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
763 for (i = 0; i < sz; i++ )
768 #endif /* FREESCALE_K70_RNGA */
770 #elif defined(CYASSL_SAFERTOS) || defined(CYASSL_LEANPSK) \
771 || defined(CYASSL_IAR_ARM) || defined(CYASSL_MDK_ARM)
773 #warning "write a real random seed!!!!, just for testing now"
775 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
778 for (i = 0; i < sz; i++ )
786 #elif defined(STM32F2_RNG)
788 #include "stm32f2xx_rng.h"
789 #include "stm32f2xx_rcc.h"
791 * Generate a RNG seed using the hardware random number generator
792 * on the STM32F2. Documentation located in STM32F2xx Standard Peripheral
793 * Library document (See note in README).
795 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
799 /* enable RNG clock source */
800 RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_RNG, ENABLE);
802 /* enable RNG peripheral */
805 for (i = 0; i < sz; i++) {
806 /* wait until RNG number is ready */
807 while(RNG_GetFlagStatus(RNG_FLAG_DRDY)== RESET) { }
810 output[i] = RNG_GetRandomNumber();
815 #elif defined(CYASSL_LPC43xx) || defined(CYASSL_STM32F2xx)
817 #warning "write a real random seed!!!!, just for testing now"
819 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
823 for (i = 0; i < sz; i++ )
829 #elif defined(CUSTOM_RAND_GENERATE)
831 /* Implement your own random generation function
832 * word32 rand_gen(void);
833 * #define CUSTOM_RAND_GENERATE rand_gen */
835 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
839 for (i = 0; i < sz; i++ )
840 output[i] = CUSTOM_RAND_GENERATE();
845 #elif defined(NO_DEV_RANDOM)
847 #error "you need to write an os specific GenerateSeed() here"
850 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
857 #else /* !USE_WINDOWS_API && !HAVE_RPT_SYS && !MICRIUM && !NO_DEV_RANDOM */
861 int GenerateSeed(OS_Seed* os, byte* output, word32 sz)
865 os->fd = open("/dev/urandom",O_RDONLY);
867 /* may still have /dev/random */
868 os->fd = open("/dev/random",O_RDONLY);
874 int len = (int)read(os->fd, output, sz);
885 sleep(0); /* context switch */
897 #endif /* USE_WINDOWS_API */