md_rand.c thread safety
[openssl.git] / crypto / rand / md_rand.c
1 /* crypto/rand/md_rand.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2000 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #ifdef MD_RAND_DEBUG
113 # ifndef NDEBUG
114 #   define NDEBUG
115 # endif
116 #endif
117
118 #include <assert.h>
119 #include <stdio.h>
120 #include <string.h>
121
122 #include "e_os.h"
123
124 #include <openssl/rand.h>
125 #include "rand_lcl.h"
126
127 #include <openssl/crypto.h>
128 #include <openssl/err.h>
129
130 #ifdef BN_DEBUG
131 # define PREDICT
132 #endif
133
134 /* #define PREDICT      1 */
135
136 #define STATE_SIZE      1023
137 static int state_num=0,state_index=0;
138 static unsigned char state[STATE_SIZE+MD_DIGEST_LENGTH];
139 static unsigned char md[MD_DIGEST_LENGTH];
140 static long md_count[2]={0,0};
141 static double entropy=0;
142 static int initialized=0;
143
144 static unsigned int crypto_lock_rand = 0; /* may be set only when a thread
145                                            * holds CRYPTO_LOCK_RAND
146                                            * (to prevent double locking) */
147 /* access to lockin_thread is synchronized by CRYPTO_LOCK_RAND2 */
148 static unsigned long locking_thread = 0; /* valid iff crypto_lock_rand is set */
149
150
151 #ifdef PREDICT
152 int rand_predictable=0;
153 #endif
154
155 const char *RAND_version="RAND" OPENSSL_VERSION_PTEXT;
156
157 static void ssleay_rand_cleanup(void);
158 static void ssleay_rand_seed(const void *buf, int num);
159 static void ssleay_rand_add(const void *buf, int num, double add_entropy);
160 static int ssleay_rand_bytes(unsigned char *buf, int num);
161 static int ssleay_rand_pseudo_bytes(unsigned char *buf, int num);
162 static int ssleay_rand_status(void);
163
164 RAND_METHOD rand_ssleay_meth={
165         ssleay_rand_seed,
166         ssleay_rand_bytes,
167         ssleay_rand_cleanup,
168         ssleay_rand_add,
169         ssleay_rand_pseudo_bytes,
170         ssleay_rand_status
171         }; 
172
173 RAND_METHOD *RAND_SSLeay(void)
174         {
175         return(&rand_ssleay_meth);
176         }
177
178 static void ssleay_rand_cleanup(void)
179         {
180         memset(state,0,sizeof(state));
181         state_num=0;
182         state_index=0;
183         memset(md,0,MD_DIGEST_LENGTH);
184         md_count[0]=0;
185         md_count[1]=0;
186         entropy=0;
187         initialized=0;
188         }
189
190 static void ssleay_rand_add(const void *buf, int num, double add)
191         {
192         int i,j,k,st_idx;
193         long md_c[2];
194         unsigned char local_md[MD_DIGEST_LENGTH];
195         MD_CTX m;
196         int do_not_lock;
197
198         /*
199          * (Based on the rand(3) manpage)
200          *
201          * The input is chopped up into units of 20 bytes (or less for
202          * the last block).  Each of these blocks is run through the hash
203          * function as follows:  The data passed to the hash function
204          * is the current 'md', the same number of bytes from the 'state'
205          * (the location determined by in incremented looping index) as
206          * the current 'block', the new key data 'block', and 'count'
207          * (which is incremented after each use).
208          * The result of this is kept in 'md' and also xored into the
209          * 'state' at the same locations that were used as input into the
210          * hash function.
211          */
212
213         /* check if we already have the lock */
214         if (crypto_lock_rand)
215                 {
216                 CRYPTO_r_lock(CRYPTO_LOCK_RAND2);
217                 do_not_lock = (locking_thread == CRYPTO_thread_id());
218                 CRYPTO_r_unlock(CRYPTO_LOCK_RAND2);
219                 }
220         else
221                 do_not_lock = 0;
222
223         if (!do_not_lock) CRYPTO_w_lock(CRYPTO_LOCK_RAND);
224         st_idx=state_index;
225
226         /* use our own copies of the counters so that even
227          * if a concurrent thread seeds with exactly the
228          * same data and uses the same subarray there's _some_
229          * difference */
230         md_c[0] = md_count[0];
231         md_c[1] = md_count[1];
232
233         memcpy(local_md, md, sizeof md);
234
235         /* state_index <= state_num <= STATE_SIZE */
236         state_index += num;
237         if (state_index >= STATE_SIZE)
238                 {
239                 state_index%=STATE_SIZE;
240                 state_num=STATE_SIZE;
241                 }
242         else if (state_num < STATE_SIZE)        
243                 {
244                 if (state_index > state_num)
245                         state_num=state_index;
246                 }
247         /* state_index <= state_num <= STATE_SIZE */
248
249         /* state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE]
250          * are what we will use now, but other threads may use them
251          * as well */
252
253         md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
254
255         if (!do_not_lock) CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
256
257         for (i=0; i<num; i+=MD_DIGEST_LENGTH)
258                 {
259                 j=(num-i);
260                 j=(j > MD_DIGEST_LENGTH)?MD_DIGEST_LENGTH:j;
261
262                 MD_Init(&m);
263                 MD_Update(&m,local_md,MD_DIGEST_LENGTH);
264                 k=(st_idx+j)-STATE_SIZE;
265                 if (k > 0)
266                         {
267                         MD_Update(&m,&(state[st_idx]),j-k);
268                         MD_Update(&m,&(state[0]),k);
269                         }
270                 else
271                         MD_Update(&m,&(state[st_idx]),j);
272                         
273                 MD_Update(&m,buf,j);
274                 MD_Update(&m,(unsigned char *)&(md_c[0]),sizeof(md_c));
275                 MD_Final(&m,local_md);
276                 md_c[1]++;
277
278                 buf=(const char *)buf + j;
279
280                 for (k=0; k<j; k++)
281                         {
282                         /* Parallel threads may interfere with this,
283                          * but always each byte of the new state is
284                          * the XOR of some previous value of its
285                          * and local_md (itermediate values may be lost).
286                          * Alway using locking could hurt performance more
287                          * than necessary given that conflicts occur only
288                          * when the total seeding is longer than the random
289                          * state. */
290                         state[st_idx++]^=local_md[k];
291                         if (st_idx >= STATE_SIZE)
292                                 st_idx=0;
293                         }
294                 }
295         memset((char *)&m,0,sizeof(m));
296
297         if (!do_not_lock) CRYPTO_w_lock(CRYPTO_LOCK_RAND);
298         /* Don't just copy back local_md into md -- this could mean that
299          * other thread's seeding remains without effect (except for
300          * the incremented counter).  By XORing it we keep at least as
301          * much entropy as fits into md. */
302         for (k = 0; k < sizeof md; k++)
303                 {
304                 md[k] ^= local_md[k];
305                 }
306         if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
307             entropy += add;
308         if (!do_not_lock) CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
309         
310 #if !defined(OPENSSL_THREADS) && !defined(OPENSSL_SYS_WIN32)
311         assert(md_c[1] == md_count[1]);
312 #endif
313         }
314
315 static void ssleay_rand_seed(const void *buf, int num)
316         {
317         ssleay_rand_add(buf, num, num);
318         }
319
320 static int ssleay_rand_bytes(unsigned char *buf, int num)
321         {
322         static volatile int stirred_pool = 0;
323         int i,j,k,st_num,st_idx;
324         int num_ceil;
325         int ok;
326         long md_c[2];
327         unsigned char local_md[MD_DIGEST_LENGTH];
328         MD_CTX m;
329 #ifndef GETPID_IS_MEANINGLESS
330         pid_t curr_pid = getpid();
331 #endif
332         int do_stir_pool = 0;
333
334 #ifdef PREDICT
335         if (rand_predictable)
336                 {
337                 static unsigned char val=0;
338
339                 for (i=0; i<num; i++)
340                         buf[i]=val++;
341                 return(1);
342                 }
343 #endif
344
345         if (num <= 0)
346                 return 1;
347         
348         /* round upwards to multiple of MD_DIGEST_LENGTH/2 */
349         num_ceil = (1 + (num-1)/(MD_DIGEST_LENGTH/2)) * (MD_DIGEST_LENGTH/2);
350
351         /*
352          * (Based on the rand(3) manpage:)
353          *
354          * For each group of 10 bytes (or less), we do the following:
355          *
356          * Input into the hash function the local 'md' (which is initialized from
357          * the global 'md' before any bytes are generated), the bytes that are to
358          * be overwritten by the random bytes, and bytes from the 'state'
359          * (incrementing looping index). From this digest output (which is kept
360          * in 'md'), the top (up to) 10 bytes are returned to the caller and the
361          * bottom 10 bytes are xored into the 'state'.
362          * 
363          * Finally, after we have finished 'num' random bytes for the
364          * caller, 'count' (which is incremented) and the local and global 'md'
365          * are fed into the hash function and the results are kept in the
366          * global 'md'.
367          */
368
369         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
370
371         /* prevent ssleay_rand_bytes() from trying to obtain the lock again */
372         CRYPTO_w_lock(CRYPTO_LOCK_RAND2);
373         locking_thread = CRYPTO_thread_id();
374         CRYPTO_w_unlock(CRYPTO_LOCK_RAND2);
375         crypto_lock_rand = 1;
376
377         if (!initialized)
378                 {
379                 RAND_poll();
380                 initialized = 1;
381                 }
382         
383         if (!stirred_pool)
384                 do_stir_pool = 1;
385         
386         ok = (entropy >= ENTROPY_NEEDED);
387         if (!ok)
388                 {
389                 /* If the PRNG state is not yet unpredictable, then seeing
390                  * the PRNG output may help attackers to determine the new
391                  * state; thus we have to decrease the entropy estimate.
392                  * Once we've had enough initial seeding we don't bother to
393                  * adjust the entropy count, though, because we're not ambitious
394                  * to provide *information-theoretic* randomness.
395                  *
396                  * NOTE: This approach fails if the program forks before
397                  * we have enough entropy. Entropy should be collected
398                  * in a separate input pool and be transferred to the
399                  * output pool only when the entropy limit has been reached.
400                  */
401                 entropy -= num;
402                 if (entropy < 0)
403                         entropy = 0;
404                 }
405
406         if (do_stir_pool)
407                 {
408                 /* In the output function only half of 'md' remains secret,
409                  * so we better make sure that the required entropy gets
410                  * 'evenly distributed' through 'state', our randomness pool.
411                  * The input function (ssleay_rand_add) chains all of 'md',
412                  * which makes it more suitable for this purpose.
413                  */
414
415                 int n = STATE_SIZE; /* so that the complete pool gets accessed */
416                 while (n > 0)
417                         {
418 #if MD_DIGEST_LENGTH > 20
419 # error "Please adjust DUMMY_SEED."
420 #endif
421 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
422                         /* Note that the seed does not matter, it's just that
423                          * ssleay_rand_add expects to have something to hash. */
424                         ssleay_rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
425                         n -= MD_DIGEST_LENGTH;
426                         }
427                 if (ok)
428                         stirred_pool = 1;
429                 }
430
431         st_idx=state_index;
432         st_num=state_num;
433         md_c[0] = md_count[0];
434         md_c[1] = md_count[1];
435         memcpy(local_md, md, sizeof md);
436
437         state_index+=num_ceil;
438         if (state_index > state_num)
439                 state_index %= state_num;
440
441         /* state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num]
442          * are now ours (but other threads may use them too) */
443
444         md_count[0] += 1;
445
446         /* before unlocking, we must clear 'crypto_lock_rand' */
447         crypto_lock_rand = 0;
448         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
449
450         while (num > 0)
451                 {
452                 /* num_ceil -= MD_DIGEST_LENGTH/2 */
453                 j=(num >= MD_DIGEST_LENGTH/2)?MD_DIGEST_LENGTH/2:num;
454                 num-=j;
455                 MD_Init(&m);
456 #ifndef GETPID_IS_MEANINGLESS
457                 if (curr_pid) /* just in the first iteration to save time */
458                         {
459                         MD_Update(&m,(unsigned char*)&curr_pid,sizeof curr_pid);
460                         curr_pid = 0;
461                         }
462 #endif
463                 MD_Update(&m,local_md,MD_DIGEST_LENGTH);
464                 MD_Update(&m,(unsigned char *)&(md_c[0]),sizeof(md_c));
465 #ifndef PURIFY
466                 MD_Update(&m,buf,j); /* purify complains */
467 #endif
468                 k=(st_idx+MD_DIGEST_LENGTH/2)-st_num;
469                 if (k > 0)
470                         {
471                         MD_Update(&m,&(state[st_idx]),MD_DIGEST_LENGTH/2-k);
472                         MD_Update(&m,&(state[0]),k);
473                         }
474                 else
475                         MD_Update(&m,&(state[st_idx]),MD_DIGEST_LENGTH/2);
476                 MD_Final(&m,local_md);
477
478                 for (i=0; i<MD_DIGEST_LENGTH/2; i++)
479                         {
480                         state[st_idx++]^=local_md[i]; /* may compete with other threads */
481                         if (st_idx >= st_num)
482                                 st_idx=0;
483                         if (i < j)
484                                 *(buf++)=local_md[i+MD_DIGEST_LENGTH/2];
485                         }
486                 }
487
488         MD_Init(&m);
489         MD_Update(&m,(unsigned char *)&(md_c[0]),sizeof(md_c));
490         MD_Update(&m,local_md,MD_DIGEST_LENGTH);
491         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
492         MD_Update(&m,md,MD_DIGEST_LENGTH);
493         MD_Final(&m,md);
494         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
495
496         memset(&m,0,sizeof(m));
497         if (ok)
498                 return(1);
499         else
500                 {
501                 RANDerr(RAND_F_SSLEAY_RAND_BYTES,RAND_R_PRNG_NOT_SEEDED);
502                 ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
503                         "http://www.openssl.org/support/faq.html");
504                 return(0);
505                 }
506         }
507
508 /* pseudo-random bytes that are guaranteed to be unique but not
509    unpredictable */
510 static int ssleay_rand_pseudo_bytes(unsigned char *buf, int num) 
511         {
512         int ret;
513         unsigned long err;
514
515         ret = RAND_bytes(buf, num);
516         if (ret == 0)
517                 {
518                 err = ERR_peek_error();
519                 if (ERR_GET_LIB(err) == ERR_LIB_RAND &&
520                     ERR_GET_REASON(err) == RAND_R_PRNG_NOT_SEEDED)
521                         (void)ERR_get_error();
522                 }
523         return (ret);
524         }
525
526 static int ssleay_rand_status(void)
527         {
528         int ret;
529         int do_not_lock;
530
531         /* check if we already have the lock
532          * (could happen if a RAND_poll() implementation calls RAND_status()) */
533         if (crypto_lock_rand)
534                 {
535                 CRYPTO_r_lock(CRYPTO_LOCK_RAND2);
536                 do_not_lock = (locking_thread == CRYPTO_thread_id());
537                 CRYPTO_r_unlock(CRYPTO_LOCK_RAND2);
538                 }
539         else
540                 do_not_lock = 0;
541         
542         if (!do_not_lock)
543                 {
544                 CRYPTO_w_lock(CRYPTO_LOCK_RAND);
545                 
546                 /* prevent ssleay_rand_bytes() from trying to obtain the lock again */
547                 CRYPTO_w_lock(CRYPTO_LOCK_RAND2);
548                 locking_thread = CRYPTO_thread_id();
549                 CRYPTO_w_unlock(CRYPTO_LOCK_RAND2);
550                 crypto_lock_rand = 1;
551                 }
552         
553         if (!initialized)
554                 {
555                 RAND_poll();
556                 initialized = 1;
557                 }
558
559         ret = entropy >= ENTROPY_NEEDED;
560
561         if (!do_not_lock)
562                 {
563                 /* before unlocking, we must clear 'crypto_lock_rand' */
564                 crypto_lock_rand = 0;
565                 
566                 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
567                 }
568         
569         return ret;
570         }