Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(620)

Side by Side Diff: nss/lib/freebl/drbg.c

Issue 2078763002: Delete bundled copy of NSS and replace with README. (Closed) Base URL: https://chromium.googlesource.com/chromium/deps/nss@master
Patch Set: Delete bundled copy of NSS and replace with README. Created 4 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « nss/lib/freebl/dh.c ('k') | nss/lib/freebl/dsa.c » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 #ifdef FREEBL_NO_DEPEND
6 #include "stubs.h"
7 #endif
8
9 #include "prerror.h"
10 #include "secerr.h"
11
12 #include "prtypes.h"
13 #include "prinit.h"
14 #include "blapi.h"
15 #include "blapii.h"
16 #include "nssilock.h"
17 #include "secitem.h"
18 #include "sha_fast.h"
19 #include "sha256.h"
20 #include "secrng.h" /* for RNG_SystemRNG() */
21 #include "secmpi.h"
22
23 /* PRNG_SEEDLEN defined in NIST SP 800-90 section 10.1
24 * for SHA-1, SHA-224, and SHA-256 it's 440 bits.
25 * for SHA-384 and SHA-512 it's 888 bits */
26 #define PRNG_SEEDLEN (440/PR_BITS_PER_BYTE)
27 #define PRNG_MAX_ADDITIONAL_BYTES PR_INT64(0x100000000)
28 /* 2^35 bits or 2^32 bytes */
29 #define PRNG_MAX_REQUEST_SIZE 0x10000 /* 2^19 bits or 2^16 bytes */
30 #define PRNG_ADDITONAL_DATA_CACHE_SIZE (8*1024) /* must be less than
31 * PRNG_MAX_ADDITIONAL_BYTES
32 */
33
34 /* RESEED_COUNT is how many calls to the prng before we need to reseed
35 * under normal NIST rules, you must return an error. In the NSS case, we
36 * self-reseed with RNG_SystemRNG(). Count can be a large number. For code
37 * simplicity, we specify count with 2 components: RESEED_BYTE (which is
38 * the same as LOG256(RESEED_COUNT)) and RESEED_VALUE (which is the same as
39 * RESEED_COUNT / (256 ^ RESEED_BYTE)). Another way to look at this is
40 * RESEED_COUNT = RESEED_VALUE * (256 ^ RESEED_BYTE). For Hash based DRBG
41 * we use the maximum count value, 2^48, or RESEED_BYTE=6 and RESEED_VALUE=1
42 */
43 #define RESEED_BYTE 6
44 #define RESEED_VALUE 1
45
46 #define PRNG_RESET_RESEED_COUNT(rng) \
47 PORT_Memset((rng)->reseed_counter, 0, sizeof (rng)->reseed_counter); \
48 (rng)->reseed_counter[RESEED_BYTE] = 1;
49
50
51 /*
52 * The actual values of this enum are specified in SP 800-90, 10.1.1.*
53 * The spec does not name the types, it only uses bare values
54 */
55 typedef enum {
56 prngCGenerateType = 0, /* used when creating a new 'C' */
57 prngReseedType = 1, /* used in reseeding */
58 prngAdditionalDataType = 2, /* used in mixing additional data */
59 prngGenerateByteType = 3 /* used when mixing internal state while
60 * generating bytes */
61 } prngVTypes;
62
63 /*
64 * Global RNG context
65 */
66 struct RNGContextStr {
67 PZLock *lock; /* Lock to serialize access to global rng */
68 /*
69 * NOTE, a number of steps in the drbg algorithm need to hash
70 * V_type || V. The code, therefore, depends on the V array following
71 * immediately after V_type to avoid extra copies. To accomplish this
72 * in a way that compiliers can't perturb, we declare V_type and V
73 * as a V_Data array and reference them by macros */
74 PRUint8 V_Data[PRNG_SEEDLEN+1]; /* internal state variables */
75 #define V_type V_Data[0]
76 #define V(rng) (((rng)->V_Data)+1)
77 #define VSize(rng) ((sizeof (rng)->V_Data) -1)
78 PRUint8 C[PRNG_SEEDLEN]; /* internal state variables */
79 PRUint8 oldV[PRNG_SEEDLEN]; /* for continuous rng checking */
80 /* If we get calls for the PRNG to return less than the length of our
81 * hash, we extend the request for a full hash (since we'll be doing
82 * the full hash anyway). Future requests for random numbers are fulfilled
83 * from the remainder of the bytes we generated. Requests for bytes longer
84 * than the hash size are fulfilled directly from the HashGen function
85 * of the random number generator. */
86 PRUint8 reseed_counter[RESEED_BYTE+1]; /* number of requests since the
87 * last reseed. Need only be
88 * big enough to hold the whole
89 * reseed count */
90 PRUint8 data[SHA256_LENGTH]; /* when we request less than a block
91 * save the rest of the rng output for
92 * another partial block */
93 PRUint8 dataAvail; /* # bytes of output available in our cache,
94 * [0...SHA256_LENGTH] */
95 /* store additional data that has been shovelled off to us by
96 * RNG_RandomUpdate. */
97 PRUint8 additionalDataCache[PRNG_ADDITONAL_DATA_CACHE_SIZE];
98 PRUint32 additionalAvail;
99 PRBool isValid; /* false if RNG reaches an invalid state */
100 };
101
102 typedef struct RNGContextStr RNGContext;
103 static RNGContext *globalrng = NULL;
104 static RNGContext theGlobalRng;
105
106
107 /*
108 * The next several functions are derived from the NIST SP 800-90
109 * spec. In these functions, an attempt was made to use names consistent
110 * with the names in the spec, even if they differ from normal NSS usage.
111 */
112
113 /*
114 * Hash Derive function defined in NISP SP 800-90 Section 10.4.1.
115 * This function is used in the Instantiate and Reseed functions.
116 *
117 * NOTE: requested_bytes cannot overlap with input_string_1 or input_string_2.
118 * input_string_1 and input_string_2 are logically concatentated.
119 * input_string_1 must be supplied.
120 * if input_string_2 is not supplied, NULL should be passed for this parameter.
121 */
122 static SECStatus
123 prng_Hash_df(PRUint8 *requested_bytes, unsigned int no_of_bytes_to_return,
124 const PRUint8 *input_string_1, unsigned int input_string_1_len,
125 const PRUint8 *input_string_2, unsigned int input_string_2_len)
126 {
127 SHA256Context ctx;
128 PRUint32 tmp;
129 PRUint8 counter;
130
131 tmp=SHA_HTONL(no_of_bytes_to_return*8);
132
133 for (counter = 1 ; no_of_bytes_to_return > 0; counter++) {
134 unsigned int hash_return_len;
135 SHA256_Begin(&ctx);
136 SHA256_Update(&ctx, &counter, 1);
137 SHA256_Update(&ctx, (unsigned char *)&tmp, sizeof tmp);
138 SHA256_Update(&ctx, input_string_1, input_string_1_len);
139 if (input_string_2) {
140 SHA256_Update(&ctx, input_string_2, input_string_2_len);
141 }
142 SHA256_End(&ctx, requested_bytes, &hash_return_len,
143 no_of_bytes_to_return);
144 requested_bytes += hash_return_len;
145 no_of_bytes_to_return -= hash_return_len;
146 }
147 return SECSuccess;
148 }
149
150
151 /*
152 * Hash_DRBG Instantiate NIST SP 800-80 10.1.1.2
153 *
154 * NOTE: bytes & len are entropy || nonce || personalization_string. In
155 * normal operation, NSS calculates them all together in a single call.
156 */
157 static SECStatus
158 prng_instantiate(RNGContext *rng, const PRUint8 *bytes, unsigned int len)
159 {
160 if (len < PRNG_SEEDLEN) {
161 /* if the seedlen is to small, it's probably because we failed to get
162 * enough random data */
163 PORT_SetError(SEC_ERROR_NEED_RANDOM);
164 return SECFailure;
165 }
166 prng_Hash_df(V(rng), VSize(rng), bytes, len, NULL, 0);
167 rng->V_type = prngCGenerateType;
168 prng_Hash_df(rng->C,sizeof rng->C,rng->V_Data,sizeof rng->V_Data,NULL,0);
169 PRNG_RESET_RESEED_COUNT(rng)
170 return SECSuccess;
171 }
172
173
174 /*
175 * Update the global random number generator with more seeding
176 * material. Use the Hash_DRBG reseed algorithm from NIST SP-800-90
177 * section 10.1.1.3
178 *
179 * If entropy is NULL, it is fetched from the noise generator.
180 */
181 static SECStatus
182 prng_reseed(RNGContext *rng, const PRUint8 *entropy, unsigned int entropy_len,
183 const PRUint8 *additional_input, unsigned int additional_input_len)
184 {
185 PRUint8 noiseData[(sizeof rng->V_Data)+PRNG_SEEDLEN];
186 PRUint8 *noise = &noiseData[0];
187
188 /* if entropy wasn't supplied, fetch it. (normal operation case) */
189 if (entropy == NULL) {
190 entropy_len = (unsigned int) RNG_SystemRNG(
191 &noiseData[sizeof rng->V_Data], PRNG_SEEDLEN);
192 } else {
193 /* NOTE: this code is only available for testing, not to applications */
194 /* if entropy was too big for the stack variable, get it from malloc */
195 if (entropy_len > PRNG_SEEDLEN) {
196 noise = PORT_Alloc(entropy_len + (sizeof rng->V_Data));
197 if (noise == NULL) {
198 return SECFailure;
199 }
200 }
201 PORT_Memcpy(&noise[sizeof rng->V_Data],entropy, entropy_len);
202 }
203
204 if (entropy_len < 256/PR_BITS_PER_BYTE) {
205 /* noise == &noiseData[0] at this point, so nothing to free */
206 PORT_SetError(SEC_ERROR_NEED_RANDOM);
207 return SECFailure;
208 }
209
210 rng->V_type = prngReseedType;
211 PORT_Memcpy(noise, rng->V_Data, sizeof rng->V_Data);
212 prng_Hash_df(V(rng), VSize(rng), noise, (sizeof rng->V_Data) + entropy_len,
213 additional_input, additional_input_len);
214 /* clear potential CSP */
215 PORT_Memset(noise, 0, (sizeof rng->V_Data) + entropy_len);
216 rng->V_type = prngCGenerateType;
217 prng_Hash_df(rng->C,sizeof rng->C,rng->V_Data,sizeof rng->V_Data,NULL,0);
218 PRNG_RESET_RESEED_COUNT(rng)
219
220 if (noise != &noiseData[0]) {
221 PORT_Free(noise);
222 }
223 return SECSuccess;
224 }
225
226 /*
227 * SP 800-90 requires we rerun our health tests on reseed
228 */
229 static SECStatus
230 prng_reseed_test(RNGContext *rng, const PRUint8 *entropy,
231 unsigned int entropy_len, const PRUint8 *additional_input,
232 unsigned int additional_input_len)
233 {
234 SECStatus rv;
235
236 /* do health checks in FIPS mode */
237 rv = PRNGTEST_RunHealthTests();
238 if (rv != SECSuccess) {
239 /* error set by PRNGTEST_RunHealTests() */
240 rng->isValid = PR_FALSE;
241 return SECFailure;
242 }
243 return prng_reseed(rng, entropy, entropy_len,
244 additional_input, additional_input_len);
245 }
246
247 /*
248 * build some fast inline functions for adding.
249 */
250 #define PRNG_ADD_CARRY_ONLY(dest, start, carry) \
251 { \
252 int k1; \
253 for (k1 = start; carry && k1 >= 0; k1--) { \
254 carry = !(++dest[k1]); \
255 } \
256 }
257
258 /*
259 * NOTE: dest must be an array for the following to work.
260 */
261 #define PRNG_ADD_BITS(dest, dest_len, add, len, carry) \
262 carry = 0; \
263 PORT_Assert((dest_len) >= (len)); \
264 { \
265 int k1, k2; \
266 for (k1 = dest_len - 1, k2 = len - 1; k2 >= 0; --k1, --k2) { \
267 carry += dest[k1] + add[k2]; \
268 dest[k1] = (PRUint8) carry; \
269 carry >>= 8; \
270 } \
271 }
272
273 #define PRNG_ADD_BITS_AND_CARRY(dest, dest_len, add, len, carry) \
274 PRNG_ADD_BITS(dest, dest_len, add, len, carry) \
275 PRNG_ADD_CARRY_ONLY(dest, dest_len - len, carry)
276
277 /*
278 * This function expands the internal state of the prng to fulfill any number
279 * of bytes we need for this request. We only use this call if we need more
280 * than can be supplied by a single call to SHA256_HashBuf.
281 *
282 * This function is specified in NIST SP 800-90 section 10.1.1.4, Hashgen
283 */
284 static void
285 prng_Hashgen(RNGContext *rng, PRUint8 *returned_bytes,
286 unsigned int no_of_returned_bytes)
287 {
288 PRUint8 data[VSize(rng)];
289
290 PORT_Memcpy(data, V(rng), VSize(rng));
291 while (no_of_returned_bytes) {
292 SHA256Context ctx;
293 unsigned int len;
294 unsigned int carry;
295
296 SHA256_Begin(&ctx);
297 SHA256_Update(&ctx, data, sizeof data);
298 SHA256_End(&ctx, returned_bytes, &len, no_of_returned_bytes);
299 returned_bytes += len;
300 no_of_returned_bytes -= len;
301 /* The carry parameter is a bool (increment or not).
302 * This increments data if no_of_returned_bytes is not zero */
303 carry = no_of_returned_bytes;
304 PRNG_ADD_CARRY_ONLY(data, (sizeof data)- 1, carry);
305 }
306 PORT_Memset(data, 0, sizeof data);
307 }
308
309 /*
310 * Generates new random bytes and advances the internal prng state.
311 * additional bytes are only used in algorithm testing.
312 *
313 * This function is specified in NIST SP 800-90 section 10.1.1.4
314 */
315 static SECStatus
316 prng_generateNewBytes(RNGContext *rng,
317 PRUint8 *returned_bytes, unsigned int no_of_returned_bytes,
318 const PRUint8 *additional_input,
319 unsigned int additional_input_len)
320 {
321 PRUint8 H[SHA256_LENGTH]; /* both H and w since they
322 * aren't used concurrently */
323 unsigned int carry;
324
325 if (!rng->isValid) {
326 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
327 return SECFailure;
328 }
329 /* This code only triggers during tests, normal
330 * prng operation does not use additional_input */
331 if (additional_input){
332 SHA256Context ctx;
333 /* NIST SP 800-90 defines two temporaries in their calculations,
334 * w and H. These temporaries are the same lengths, and used
335 * at different times, so we use the following macro to collapse
336 * them to the same variable, but keeping their unique names for
337 * easy comparison to the spec */
338 #define w H
339 rng->V_type = prngAdditionalDataType;
340 SHA256_Begin(&ctx);
341 SHA256_Update(&ctx, rng->V_Data, sizeof rng->V_Data);
342 SHA256_Update(&ctx, additional_input, additional_input_len);
343 SHA256_End(&ctx, w, NULL, sizeof w);
344 PRNG_ADD_BITS_AND_CARRY(V(rng), VSize(rng), w, sizeof w, carry)
345 PORT_Memset(w, 0, sizeof w);
346 #undef w
347 }
348
349 if (no_of_returned_bytes == SHA256_LENGTH) {
350 /* short_cut to hashbuf and save a copy and a clear */
351 SHA256_HashBuf(returned_bytes, V(rng), VSize(rng) );
352 } else {
353 prng_Hashgen(rng, returned_bytes, no_of_returned_bytes);
354 }
355 /* advance our internal state... */
356 rng->V_type = prngGenerateByteType;
357 SHA256_HashBuf(H, rng->V_Data, sizeof rng->V_Data);
358 PRNG_ADD_BITS_AND_CARRY(V(rng), VSize(rng), H, sizeof H, carry)
359 PRNG_ADD_BITS(V(rng), VSize(rng), rng->C, sizeof rng->C, carry);
360 PRNG_ADD_BITS_AND_CARRY(V(rng), VSize(rng), rng->reseed_counter,
361 sizeof rng->reseed_counter, carry)
362 carry = 1;
363 PRNG_ADD_CARRY_ONLY(rng->reseed_counter,(sizeof rng->reseed_counter)-1, carr y);
364
365 /* continuous rng check */
366 if (memcmp(V(rng), rng->oldV, sizeof rng->oldV) == 0) {
367 rng->isValid = PR_FALSE;
368 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
369 return SECFailure;
370 }
371 PORT_Memcpy(rng->oldV, V(rng), sizeof rng->oldV);
372 return SECSuccess;
373 }
374
375 /* Use NSPR to prevent RNG_RNGInit from being called from separate
376 * threads, creating a race condition.
377 */
378 static const PRCallOnceType pristineCallOnce;
379 static PRCallOnceType coRNGInit;
380 static PRStatus rng_init(void)
381 {
382 PRUint8 bytes[PRNG_SEEDLEN*2]; /* entropy + nonce */
383 unsigned int numBytes;
384 SECStatus rv = SECSuccess;
385
386 if (globalrng == NULL) {
387 /* bytes needs to have enough space to hold
388 * a SHA256 hash value. Blow up at compile time if this isn't true */
389 PR_STATIC_ASSERT(sizeof(bytes) >= SHA256_LENGTH);
390 /* create a new global RNG context */
391 globalrng = &theGlobalRng;
392 PORT_Assert(NULL == globalrng->lock);
393 /* create a lock for it */
394 globalrng->lock = PZ_NewLock(nssILockOther);
395 if (globalrng->lock == NULL) {
396 globalrng = NULL;
397 PORT_SetError(PR_OUT_OF_MEMORY_ERROR);
398 return PR_FAILURE;
399 }
400
401 /* Try to get some seed data for the RNG */
402 numBytes = (unsigned int) RNG_SystemRNG(bytes, sizeof bytes);
403 PORT_Assert(numBytes == 0 || numBytes == sizeof bytes);
404 if (numBytes != 0) {
405 /* if this is our first call, instantiate, otherwise reseed
406 * prng_instantiate gets a new clean state, we want to mix
407 * any previous entropy we may have collected */
408 if (V(globalrng)[0] == 0) {
409 rv = prng_instantiate(globalrng, bytes, numBytes);
410 } else {
411 rv = prng_reseed_test(globalrng, bytes, numBytes, NULL, 0);
412 }
413 memset(bytes, 0, numBytes);
414 } else {
415 PZ_DestroyLock(globalrng->lock);
416 globalrng->lock = NULL;
417 globalrng = NULL;
418 return PR_FAILURE;
419 }
420
421 if (rv != SECSuccess) {
422 return PR_FAILURE;
423 }
424 /* the RNG is in a valid state */
425 globalrng->isValid = PR_TRUE;
426
427 /* fetch one random value so that we can populate rng->oldV for our
428 * continous random number test. */
429 prng_generateNewBytes(globalrng, bytes, SHA256_LENGTH, NULL, 0);
430
431 /* Fetch more entropy into the PRNG */
432 RNG_SystemInfoForRNG();
433 }
434 return PR_SUCCESS;
435 }
436
437 /*
438 * Clean up the global RNG context
439 */
440 static void
441 prng_freeRNGContext(RNGContext *rng)
442 {
443 PRUint8 inputhash[VSize(rng) + (sizeof rng->C)];
444
445 /* destroy context lock */
446 SKIP_AFTER_FORK(PZ_DestroyLock(globalrng->lock));
447
448 /* zero global RNG context except for C & V to preserve entropy */
449 prng_Hash_df(inputhash, sizeof rng->C, rng->C, sizeof rng->C, NULL, 0);
450 prng_Hash_df(&inputhash[sizeof rng->C], VSize(rng), V(rng), VSize(rng),
451 NULL, 0);
452 memset(rng, 0, sizeof *rng);
453 memcpy(rng->C, inputhash, sizeof rng->C);
454 memcpy(V(rng), &inputhash[sizeof rng->C], VSize(rng));
455
456 memset(inputhash, 0, sizeof inputhash);
457 }
458
459 /*
460 * Public functions
461 */
462
463 /*
464 * Initialize the global RNG context and give it some seed input taken
465 * from the system. This function is thread-safe and will only allow
466 * the global context to be initialized once. The seed input is likely
467 * small, so it is imperative that RNG_RandomUpdate() be called with
468 * additional seed data before the generator is used. A good way to
469 * provide the generator with additional entropy is to call
470 * RNG_SystemInfoForRNG(). Note that C_Initialize() does exactly that.
471 */
472 SECStatus
473 RNG_RNGInit(void)
474 {
475 /* Allow only one call to initialize the context */
476 PR_CallOnce(&coRNGInit, rng_init);
477 /* Make sure there is a context */
478 return (globalrng != NULL) ? SECSuccess : SECFailure;
479 }
480
481 /*
482 ** Update the global random number generator with more seeding
483 ** material.
484 */
485 SECStatus
486 RNG_RandomUpdate(const void *data, size_t bytes)
487 {
488 SECStatus rv;
489
490 /* Make sure our assumption that size_t is unsigned is true */
491 PR_STATIC_ASSERT(((size_t)-1) > (size_t)1);
492
493 #if defined(NS_PTR_GT_32) || (defined(NSS_USE_64) && !defined(NS_PTR_LE_32))
494 /*
495 * NIST 800-90 requires us to verify our inputs. This value can
496 * come from the application, so we need to make sure it's within the
497 * spec. The spec says it must be less than 2^32 bytes (2^35 bits).
498 * This can only happen if size_t is greater than 32 bits (i.e. on
499 * most 64 bit platforms). The 90% case (perhaps 100% case), size_t
500 * is less than or equal to 32 bits if the platform is not 64 bits, and
501 * greater than 32 bits if it is a 64 bit platform. The corner
502 * cases are handled with explicit defines NS_PTR_GT_32 and NS_PTR_LE_32.
503 *
504 * In general, neither NS_PTR_GT_32 nor NS_PTR_LE_32 will need to be
505 * defined. If you trip over the next two size ASSERTS at compile time,
506 * you will need to define them for your platform.
507 *
508 * if 'sizeof(size_t) > 4' is triggered it means that we were expecting
509 * sizeof(size_t) to be greater than 4, but it wasn't. Setting
510 * NS_PTR_LE_32 will correct that mistake.
511 *
512 * if 'sizeof(size_t) <= 4' is triggered, it means that we were expecting
513 * sizeof(size_t) to be less than or equal to 4, but it wasn't. Setting
514 * NS_PTR_GT_32 will correct that mistake.
515 */
516
517 PR_STATIC_ASSERT(sizeof(size_t) > 4);
518
519 if (bytes > (size_t)PRNG_MAX_ADDITIONAL_BYTES) {
520 bytes = PRNG_MAX_ADDITIONAL_BYTES;
521 }
522 #else
523 PR_STATIC_ASSERT(sizeof(size_t) <= 4);
524 #endif
525
526 PZ_Lock(globalrng->lock);
527 /* if we're passed more than our additionalDataCache, simply
528 * call reseed with that data */
529 if (bytes > sizeof (globalrng->additionalDataCache)) {
530 rv = prng_reseed_test(globalrng, NULL, 0, data, (unsigned int) bytes);
531 /* if we aren't going to fill or overflow the buffer, just cache it */
532 } else if (bytes < ((sizeof globalrng->additionalDataCache)
533 - globalrng->additionalAvail)) {
534 PORT_Memcpy(globalrng->additionalDataCache+globalrng->additionalAvail,
535 data, bytes);
536 globalrng->additionalAvail += (PRUint32) bytes;
537 rv = SECSuccess;
538 } else {
539 /* we are going to fill or overflow the buffer. In this case we will
540 * fill the entropy buffer, reseed with it, start a new buffer with the
541 * remainder. We know the remainder will fit in the buffer because
542 * we already handled the case where bytes > the size of the buffer.
543 */
544 size_t bufRemain = (sizeof globalrng->additionalDataCache)
545 - globalrng->additionalAvail;
546 /* fill the rest of the buffer */
547 if (bufRemain) {
548 PORT_Memcpy(globalrng->additionalDataCache
549 +globalrng->additionalAvail,
550 data, bufRemain);
551 data = ((unsigned char *)data) + bufRemain;
552 bytes -= bufRemain;
553 }
554 /* reseed from buffer */
555 rv = prng_reseed_test(globalrng, NULL, 0,
556 globalrng->additionalDataCache,
557 sizeof globalrng->additionalDataCache);
558
559 /* copy the rest into the cache */
560 PORT_Memcpy(globalrng->additionalDataCache, data, bytes);
561 globalrng->additionalAvail = (PRUint32) bytes;
562 }
563
564 PZ_Unlock(globalrng->lock);
565 return rv;
566 }
567
568 /*
569 ** Generate some random bytes, using the global random number generator
570 ** object.
571 */
572 static SECStatus
573 prng_GenerateGlobalRandomBytes(RNGContext *rng,
574 void *dest, size_t len)
575 {
576 SECStatus rv = SECSuccess;
577 PRUint8 *output = dest;
578 /* check for a valid global RNG context */
579 PORT_Assert(rng != NULL);
580 if (rng == NULL) {
581 PORT_SetError(SEC_ERROR_INVALID_ARGS);
582 return SECFailure;
583 }
584 /* FIPS limits the amount of entropy available in a single request */
585 if (len > PRNG_MAX_REQUEST_SIZE) {
586 PORT_SetError(SEC_ERROR_INVALID_ARGS);
587 return SECFailure;
588 }
589 /* --- LOCKED --- */
590 PZ_Lock(rng->lock);
591 /* Check the amount of seed data in the generator. If not enough,
592 * don't produce any data.
593 */
594 if (rng->reseed_counter[0] >= RESEED_VALUE) {
595 rv = prng_reseed_test(rng, NULL, 0, NULL, 0);
596 PZ_Unlock(rng->lock);
597 if (rv != SECSuccess) {
598 return rv;
599 }
600 RNG_SystemInfoForRNG();
601 PZ_Lock(rng->lock);
602 }
603 /*
604 * see if we have enough bytes to fulfill the request.
605 */
606 if (len <= rng->dataAvail) {
607 memcpy(output, rng->data + ((sizeof rng->data) - rng->dataAvail), len);
608 memset(rng->data + ((sizeof rng->data) - rng->dataAvail), 0, len);
609 rng->dataAvail -= len;
610 rv = SECSuccess;
611 /* if we are asking for a small number of bytes, cache the rest of
612 * the bytes */
613 } else if (len < sizeof rng->data) {
614 rv = prng_generateNewBytes(rng, rng->data, sizeof rng->data,
615 rng->additionalAvail ? rng->additionalDataCache : NULL,
616 rng->additionalAvail);
617 rng->additionalAvail = 0;
618 if (rv == SECSuccess) {
619 memcpy(output, rng->data, len);
620 memset(rng->data, 0, len);
621 rng->dataAvail = (sizeof rng->data) - len;
622 }
623 /* we are asking for lots of bytes, just ask the generator to pass them */
624 } else {
625 rv = prng_generateNewBytes(rng, output, len,
626 rng->additionalAvail ? rng->additionalDataCache : NULL,
627 rng->additionalAvail);
628 rng->additionalAvail = 0;
629 }
630 PZ_Unlock(rng->lock);
631 /* --- UNLOCKED --- */
632 return rv;
633 }
634
635 /*
636 ** Generate some random bytes, using the global random number generator
637 ** object.
638 */
639 SECStatus
640 RNG_GenerateGlobalRandomBytes(void *dest, size_t len)
641 {
642 return prng_GenerateGlobalRandomBytes(globalrng, dest, len);
643 }
644
645 void
646 RNG_RNGShutdown(void)
647 {
648 /* check for a valid global RNG context */
649 PORT_Assert(globalrng != NULL);
650 if (globalrng == NULL) {
651 /* Should set a "not initialized" error code. */
652 PORT_SetError(SEC_ERROR_NO_MEMORY);
653 return;
654 }
655 /* clear */
656 prng_freeRNGContext(globalrng);
657 globalrng = NULL;
658 /* reset the callonce struct to allow a new call to RNG_RNGInit() */
659 coRNGInit = pristineCallOnce;
660 }
661
662 /*
663 * Test case interface. used by fips testing and power on self test
664 */
665 /* make sure the test context is separate from the global context, This
666 * allows us to test the internal random number generator without losing
667 * entropy we may have previously collected. */
668 RNGContext testContext;
669
670 /*
671 * Test vector API. Use NIST SP 800-90 general interface so one of the
672 * other NIST SP 800-90 algorithms may be used in the future.
673 */
674 SECStatus
675 PRNGTEST_Instantiate(const PRUint8 *entropy, unsigned int entropy_len,
676 const PRUint8 *nonce, unsigned int nonce_len,
677 const PRUint8 *personal_string, unsigned int ps_len)
678 {
679 int bytes_len = entropy_len + nonce_len + ps_len;
680 PRUint8 *bytes = NULL;
681 SECStatus rv;
682
683 if (entropy_len < 256/PR_BITS_PER_BYTE) {
684 PORT_SetError(SEC_ERROR_NEED_RANDOM);
685 return SECFailure;
686 }
687
688 bytes = PORT_Alloc(bytes_len);
689 if (bytes == NULL) {
690 PORT_SetError(SEC_ERROR_NO_MEMORY);
691 return SECFailure;
692 }
693 /* concatenate the various inputs, internally NSS only instantiates with
694 * a single long string */
695 PORT_Memcpy(bytes, entropy, entropy_len);
696 if (nonce) {
697 PORT_Memcpy(&bytes[entropy_len], nonce, nonce_len);
698 } else {
699 PORT_Assert(nonce_len == 0);
700 }
701 if (personal_string) {
702 PORT_Memcpy(&bytes[entropy_len+nonce_len], personal_string, ps_len);
703 } else {
704 PORT_Assert(ps_len == 0);
705 }
706 rv = prng_instantiate(&testContext, bytes, bytes_len);
707 PORT_ZFree(bytes, bytes_len);
708 if (rv == SECFailure) {
709 return SECFailure;
710 }
711 testContext.isValid = PR_TRUE;
712 return SECSuccess;
713 }
714
715 SECStatus
716 PRNGTEST_Reseed(const PRUint8 *entropy, unsigned int entropy_len,
717 const PRUint8 *additional, unsigned int additional_len)
718 {
719 if (!testContext.isValid) {
720 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
721 return SECFailure;
722 }
723 /* This magic input tells us to set the reseed count to it's max count,
724 * so we can simulate PRNGTEST_Generate reaching max reseed count */
725 if ((entropy == NULL) && (entropy_len == 0) &&
726 (additional == NULL) && (additional_len == 0)) {
727 testContext.reseed_counter[0] = RESEED_VALUE;
728 return SECSuccess;
729 }
730 return prng_reseed(&testContext, entropy, entropy_len, additional,
731 additional_len);
732
733 }
734
735 SECStatus
736 PRNGTEST_Generate(PRUint8 *bytes, unsigned int bytes_len,
737 const PRUint8 *additional, unsigned int additional_len)
738 {
739 SECStatus rv;
740 if (!testContext.isValid) {
741 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
742 return SECFailure;
743 }
744 /* replicate reseed test from prng_GenerateGlobalRandomBytes */
745 if (testContext.reseed_counter[0] >= RESEED_VALUE) {
746 rv = prng_reseed(&testContext, NULL, 0, NULL, 0);
747 if (rv != SECSuccess) {
748 return rv;
749 }
750 }
751 return prng_generateNewBytes(&testContext, bytes, bytes_len,
752 additional, additional_len);
753
754 }
755
756 SECStatus
757 PRNGTEST_Uninstantiate()
758 {
759 if (!testContext.isValid) {
760 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
761 return SECFailure;
762 }
763 PORT_Memset(&testContext, 0, sizeof testContext);
764 return SECSuccess;
765 }
766
767 SECStatus
768 PRNGTEST_RunHealthTests()
769 {
770 static const PRUint8 entropy[] = {
771 0x8e,0x9c,0x0d,0x25,0x75,0x22,0x04,0xf9,
772 0xc5,0x79,0x10,0x8b,0x23,0x79,0x37,0x14,
773 0x9f,0x2c,0xc7,0x0b,0x39,0xf8,0xee,0xef,
774 0x95,0x0c,0x97,0x59,0xfc,0x0a,0x85,0x41,
775 0x76,0x9d,0x6d,0x67,0x00,0x4e,0x19,0x12,
776 0x02,0x16,0x53,0xea,0xf2,0x73,0xd7,0xd6,
777 0x7f,0x7e,0xc8,0xae,0x9c,0x09,0x99,0x7d,
778 0xbb,0x9e,0x48,0x7f,0xbb,0x96,0x46,0xb3,
779 0x03,0x75,0xf8,0xc8,0x69,0x45,0x3f,0x97,
780 0x5e,0x2e,0x48,0xe1,0x5d,0x58,0x97,0x4c };
781 static const PRUint8 rng_known_result[] = {
782 0x16,0xe1,0x8c,0x57,0x21,0xd8,0xf1,0x7e,
783 0x5a,0xa0,0x16,0x0b,0x7e,0xa6,0x25,0xb4,
784 0x24,0x19,0xdb,0x54,0xfa,0x35,0x13,0x66,
785 0xbb,0xaa,0x2a,0x1b,0x22,0x33,0x2e,0x4a,
786 0x14,0x07,0x9d,0x52,0xfc,0x73,0x61,0x48,
787 0xac,0xc1,0x22,0xfc,0xa4,0xfc,0xac,0xa4,
788 0xdb,0xda,0x5b,0x27,0x33,0xc4,0xb3 };
789 static const PRUint8 reseed_entropy[] = {
790 0xc6,0x0b,0x0a,0x30,0x67,0x07,0xf4,0xe2,
791 0x24,0xa7,0x51,0x6f,0x5f,0x85,0x3e,0x5d,
792 0x67,0x97,0xb8,0x3b,0x30,0x9c,0x7a,0xb1,
793 0x52,0xc6,0x1b,0xc9,0x46,0xa8,0x62,0x79 };
794 static const PRUint8 additional_input[] = {
795 0x86,0x82,0x28,0x98,0xe7,0xcb,0x01,0x14,
796 0xae,0x87,0x4b,0x1d,0x99,0x1b,0xc7,0x41,
797 0x33,0xff,0x33,0x66,0x40,0x95,0x54,0xc6,
798 0x67,0x4d,0x40,0x2a,0x1f,0xf9,0xeb,0x65 };
799 static const PRUint8 rng_reseed_result[] = {
800 0x02,0x0c,0xc6,0x17,0x86,0x49,0xba,0xc4,
801 0x7b,0x71,0x35,0x05,0xf0,0xdb,0x4a,0xc2,
802 0x2c,0x38,0xc1,0xa4,0x42,0xe5,0x46,0x4a,
803 0x7d,0xf0,0xbe,0x47,0x88,0xb8,0x0e,0xc6,
804 0x25,0x2b,0x1d,0x13,0xef,0xa6,0x87,0x96,
805 0xa3,0x7d,0x5b,0x80,0xc2,0x38,0x76,0x61,
806 0xc7,0x80,0x5d,0x0f,0x05,0x76,0x85 };
807 static const PRUint8 rng_no_reseed_result[] = {
808 0xc4,0x40,0x41,0x8c,0xbf,0x2f,0x70,0x23,
809 0x88,0xf2,0x7b,0x30,0xc3,0xca,0x1e,0xf3,
810 0xef,0x53,0x81,0x5d,0x30,0xed,0x4c,0xf1,
811 0xff,0x89,0xa5,0xee,0x92,0xf8,0xc0,0x0f,
812 0x88,0x53,0xdf,0xb6,0x76,0xf0,0xaa,0xd3,
813 0x2e,0x1d,0x64,0x37,0x3e,0xe8,0x4a,0x02,
814 0xff,0x0a,0x7f,0xe5,0xe9,0x2b,0x6d };
815
816 SECStatus rng_status = SECSuccess;
817 PR_STATIC_ASSERT(sizeof(rng_known_result) >= sizeof(rng_reseed_result));
818 PRUint8 result[sizeof(rng_known_result)];
819
820 /********************************************/
821 /* First test instantiate error path. */
822 /* In this case we supply enough entropy, */
823 /* but not enough seed. This will trigger */
824 /* the code that checks for a entropy */
825 /* source failure. */
826 /********************************************/
827 rng_status = PRNGTEST_Instantiate(entropy, 256/PR_BITS_PER_BYTE,
828 NULL, 0, NULL, 0);
829 if (rng_status == SECSuccess) {
830 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
831 return SECFailure;
832 }
833 if (PORT_GetError() != SEC_ERROR_NEED_RANDOM) {
834 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
835 return SECFailure;
836 }
837 /* we failed with the proper error code, we can continue */
838
839 /********************************************/
840 /* Generate random bytes with a known seed. */
841 /********************************************/
842 rng_status = PRNGTEST_Instantiate(entropy, sizeof entropy,
843 NULL, 0, NULL, 0);
844 if (rng_status != SECSuccess) {
845 /* Error set by PRNGTEST_Instantiate */
846 return SECFailure;
847 }
848 rng_status = PRNGTEST_Generate(result, sizeof rng_known_result, NULL, 0);
849 if ( ( rng_status != SECSuccess) ||
850 ( PORT_Memcmp( result, rng_known_result,
851 sizeof rng_known_result ) != 0 ) ) {
852 PRNGTEST_Uninstantiate();
853 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
854 return SECFailure;
855 }
856 rng_status = PRNGTEST_Reseed(reseed_entropy, sizeof reseed_entropy,
857 additional_input, sizeof additional_input);
858 if (rng_status != SECSuccess) {
859 /* Error set by PRNG_Reseed */
860 PRNGTEST_Uninstantiate();
861 return SECFailure;
862 }
863 rng_status = PRNGTEST_Generate(result, sizeof rng_reseed_result, NULL, 0);
864 if ( ( rng_status != SECSuccess) ||
865 ( PORT_Memcmp( result, rng_reseed_result,
866 sizeof rng_reseed_result ) != 0 ) ) {
867 PRNGTEST_Uninstantiate();
868 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
869 return SECFailure;
870 }
871 /* This magic forces the reseed count to it's max count, so we can see if
872 * PRNGTEST_Generate will actually when it reaches it's count */
873 rng_status = PRNGTEST_Reseed(NULL, 0, NULL, 0);
874 if (rng_status != SECSuccess) {
875 PRNGTEST_Uninstantiate();
876 /* Error set by PRNG_Reseed */
877 return SECFailure;
878 }
879 /* This generate should now reseed */
880 rng_status = PRNGTEST_Generate(result, sizeof rng_reseed_result, NULL, 0);
881 if ( ( rng_status != SECSuccess) ||
882 /* NOTE we fail if the result is equal to the no_reseed_result.
883 * no_reseed_result is the value we would have gotten if we didn't
884 * do an automatic reseed in PRNGTEST_Generate */
885 ( PORT_Memcmp( result, rng_no_reseed_result,
886 sizeof rng_no_reseed_result ) == 0 ) ) {
887 PRNGTEST_Uninstantiate();
888 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
889 return SECFailure;
890 }
891 /* make sure reseed fails when we don't supply enough entropy */
892 rng_status = PRNGTEST_Reseed(reseed_entropy, 4, NULL, 0);
893 if (rng_status == SECSuccess) {
894 PRNGTEST_Uninstantiate();
895 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
896 return SECFailure;
897 }
898 if (PORT_GetError() != SEC_ERROR_NEED_RANDOM) {
899 PRNGTEST_Uninstantiate();
900 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
901 return SECFailure;
902 }
903 rng_status = PRNGTEST_Uninstantiate();
904 if (rng_status != SECSuccess) {
905 /* Error set by PRNG_Uninstantiate */
906 return rng_status;
907 }
908 /* make sure uninstantiate fails if the contest is not initiated (also tests
909 * if the context was cleared in the previous Uninstantiate) */
910 rng_status = PRNGTEST_Uninstantiate();
911 if (rng_status == SECSuccess) {
912 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
913 return SECFailure;
914 }
915 if (PORT_GetError() != SEC_ERROR_LIBRARY_FAILURE) {
916 return rng_status;
917 }
918
919 return SECSuccess;
920 }
OLDNEW
« no previous file with comments | « nss/lib/freebl/dh.c ('k') | nss/lib/freebl/dsa.c » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698