That's it, I've seen questions about this one time too many for
[openssl.git] / crypto / rand / md_rand.c
index 1a840220fcf882bef67feb4677af1037b0566596..668da9549997cc9b2586331d05ef4e574b1f8e48 100644 (file)
  * copied and put under another distribution licence
  * [including the GNU Public Licence.]
  */
+/* ====================================================================
+ * Copyright (c) 1998-2000 The OpenSSL Project.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer. 
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ *    software must display the following acknowledgment:
+ *    "This product includes software developed by the OpenSSL Project
+ *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
+ *
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ *    endorse or promote products derived from this software without
+ *    prior written permission. For written permission, please contact
+ *    openssl-core@openssl.org.
+ *
+ * 5. Products derived from this software may not be called "OpenSSL"
+ *    nor may "OpenSSL" appear in their names without prior written
+ *    permission of the OpenSSL Project.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ *    acknowledgment:
+ *    "This product includes software developed by the OpenSSL Project
+ *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com).  This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+ *
+ */
 
-#define ENTROPY_NEEDED 32  /* require 128 bits of randomness */
+#define ENTROPY_NEEDED 20  /* require 160 bits = 20 bytes of randomness */
 
-#ifndef MD_RAND_DEBUG
+#ifdef MD_RAND_DEBUG
 # ifndef NDEBUG
 #   define NDEBUG
 # endif
 
 #include <openssl/rand.h>
 
+#ifdef BN_DEBUG
+# define PREDICT
+#endif
+
 /* #define NORAND      1 */
 /* #define PREDICT     1 */
 
@@ -138,15 +195,21 @@ static int state_num=0,state_index=0;
 static unsigned char state[STATE_SIZE+MD_DIGEST_LENGTH];
 static unsigned char md[MD_DIGEST_LENGTH];
 static long md_count[2]={0,0};
-static int entropy=0;
+static double entropy=0;
+static int initialized=0;
+
+#ifdef PREDICT
+int rand_predictable=0;
+#endif
 
 const char *RAND_version="RAND" OPENSSL_VERSION_PTEXT;
 
 static void ssleay_rand_cleanup(void);
 static void ssleay_rand_seed(const void *buf, int num);
-static void ssleay_rand_add(const void *buf, int num, int add_entropy);
+static void ssleay_rand_add(const void *buf, int num, double add_entropy);
 static int ssleay_rand_bytes(unsigned char *buf, int num);
 static int ssleay_rand_pseudo_bytes(unsigned char *buf, int num);
+static int ssleay_rand_status(void);
 
 RAND_METHOD rand_ssleay_meth={
        ssleay_rand_seed,
@@ -154,6 +217,7 @@ RAND_METHOD rand_ssleay_meth={
        ssleay_rand_cleanup,
        ssleay_rand_add,
        ssleay_rand_pseudo_bytes,
+       ssleay_rand_status
        }; 
 
 RAND_METHOD *RAND_SSLeay(void)
@@ -172,7 +236,7 @@ static void ssleay_rand_cleanup(void)
        entropy=0;
        }
 
-static void ssleay_rand_add(const void *buf, int num, int add)
+static void ssleay_rand_add(const void *buf, int num, double add)
        {
        int i,j,k,st_idx;
        long md_c[2];
@@ -186,9 +250,9 @@ static void ssleay_rand_add(const void *buf, int num, int add)
        /*
         * (Based on the rand(3) manpage)
         *
-        * The input is chopped up into units of 16 bytes (or less for
+        * The input is chopped up into units of 20 bytes (or less for
         * the last block).  Each of these blocks is run through the hash
-        * function as follow:  The data passed to the hash function
+        * function as follows:  The data passed to the hash function
         * is the current 'md', the same number of bytes from the 'state'
         * (the location determined by in incremented looping index) as
         * the current 'block', the new key data 'block', and 'count'
@@ -281,12 +345,13 @@ static void ssleay_rand_add(const void *buf, int num, int add)
                {
                md[k] ^= local_md[k];
                }
+       if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
+           entropy += add;
        CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
        
 #ifndef THREADS        
        assert(md_c[1] == md_count[1]);
 #endif
-       entropy += add;
        }
 
 static void ssleay_rand_seed(const void *buf, int num)
@@ -294,94 +359,152 @@ static void ssleay_rand_seed(const void *buf, int num)
        ssleay_rand_add(buf, num, num);
        }
 
+static void ssleay_rand_initialize(void) /* not exported in RAND_METHOD */
+       {
+       unsigned long l;
+#ifndef GETPID_IS_MEANINGLESS
+       pid_t curr_pid = getpid();
+#endif
+#ifdef DEVRANDOM
+       FILE *fh;
+#endif
+
+#ifdef NORAND
+       return;
+#endif
+
+       CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
+       /* put in some default random data, we need more than just this */
+#ifndef GETPID_IS_MEANINGLESS
+       l=curr_pid;
+       RAND_add(&l,sizeof(l),0);
+       l=getuid();
+       RAND_add(&l,sizeof(l),0);
+#endif
+       l=time(NULL);
+       RAND_add(&l,sizeof(l),0);
+
+#ifdef DEVRANDOM
+       /* Use a random entropy pool device. Linux, FreeBSD and OpenBSD
+        * have this. Use /dev/urandom if you can as /dev/random may block
+        * if it runs out of random entries.  */
+
+       if ((fh = fopen(DEVRANDOM, "r")) != NULL)
+               {
+               unsigned char tmpbuf[ENTROPY_NEEDED];
+               int n;
+               
+               setvbuf(fh, NULL, _IONBF, 0);
+               n=fread((unsigned char *)tmpbuf,1,ENTROPY_NEEDED,fh);
+               fclose(fh);
+               RAND_add(tmpbuf,sizeof tmpbuf,n);
+               memset(tmpbuf,0,n);
+               }
+#endif
+#ifdef PURIFY
+       memset(state,0,STATE_SIZE);
+       memset(md,0,MD_DIGEST_LENGTH);
+#endif
+       CRYPTO_w_lock(CRYPTO_LOCK_RAND);
+       initialized=1;
+       }
+
 static int ssleay_rand_bytes(unsigned char *buf, int num)
        {
+       static volatile int stirred_pool = 0;
        int i,j,k,st_num,st_idx;
        int ok;
        long md_c[2];
        unsigned char local_md[MD_DIGEST_LENGTH];
        MD_CTX m;
-       static int init=1;
-       unsigned long l;
 #ifndef GETPID_IS_MEANINGLESS
        pid_t curr_pid = getpid();
 #endif
-#ifdef DEVRANDOM
-       FILE *fh;
-#endif
+       int do_stir_pool = 0;
 
 #ifdef PREDICT
-       {
-       static unsigned char val=0;
+       if (rand_predictable)
+               {
+               static unsigned char val=0;
 
-       for (i=0; i<num; i++)
-               buf[i]=val++;
-       return(1);
-       }
+               for (i=0; i<num; i++)
+                       buf[i]=val++;
+               return(1);
+               }
 #endif
 
        /*
-        * (Based on doc/ssleay.txt, section rand.doc:)
+        * (Based on the rand(3) manpage:)
         *
-        * For each group of 8 bytes (or less), we do the following,
+        * For each group of 10 bytes (or less), we do the following:
         *
-        * Input into MD5, the top 8 bytes from 'md', the byte that are
-        * to be overwritten by the random bytes and bytes from the
+        * Input into the hash function the top 10 bytes from the
+        * local 'md' (which is initialized from the global 'md'
+        * before any bytes are generated), the bytes that are
+        * to be overwritten by the random bytes, and bytes from the
         * 'state' (incrementing looping index).  From this digest output
-        * (which is kept in 'md'), the top (upto) 8 bytes are
-        * returned to the caller and the bottom (upto) 8 bytes are xored
+        * (which is kept in 'md'), the top (up to) 10 bytes are
+        * returned to the caller and the bottom (up to) 10 bytes are xored
         * into the 'state'.
         * Finally, after we have finished 'num' random bytes for the
-        * caller, 'count' (which is incremented) and the local and globl 'md'
-        * are fed into MD5 and the results are kept in the global 'md'.
+        * caller, 'count' (which is incremented) and the local and global 'md'
+        * are fed into the hash function and the results are kept in the
+        * global 'md'.
         */
 
        CRYPTO_w_lock(CRYPTO_LOCK_RAND);
 
-       if (init)
+       if (!initialized)
+               ssleay_rand_initialize();
+
+       if (!stirred_pool)
+               do_stir_pool = 1;
+       
+       ok = (entropy >= ENTROPY_NEEDED);
+       if (!ok)
                {
-               CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
-               /* put in some default random data, we need more than
-                * just this */
-               RAND_add(&m,sizeof(m),0);
-#ifndef GETPID_IS_MEANINGLESS
-               l=curr_pid;
-               RAND_add(&l,sizeof(l),0);
-               l=getuid();
-               RAND_add(&l,sizeof(l),0);
-#endif
-               l=time(NULL);
-               RAND_add(&l,sizeof(l),0);
+               /* If the PRNG state is not yet unpredictable, then seeing
+                * the PRNG output may help attackers to determine the new
+                * state; thus we have to decrease the entropy estimate.
+                * Once we've had enough initial seeding we don't bother to
+                * adjust the entropy count, though, because we're not ambitious
+                * to provide *information-theoretic* randomness.
+                *
+                * NOTE: This approach fails if the program forks before
+                * we have enough entropy. Entropy should be collected
+                * in a separate input pool and be transferred to the
+                * output pool only when the entropy limit has been reached.
+                */
+               entropy -= num;
+               if (entropy < 0)
+                       entropy = 0;
+               }
 
-#ifdef DEVRANDOM
-               /* 
-                * Use a random entropy pool device.
-                * Linux 1.3.x and FreeBSD-Current has 
-                * this. Use /dev/urandom if you can
-                * as /dev/random will block if it runs out
-                * of random entries.
+       if (do_stir_pool)
+               {
+               /* Our output function chains only half of 'md', so we better
+                * make sure that the required entropy gets 'evenly distributed'
+                * through 'state', our randomness pool.  The input function
+                * (ssleay_rand_add) chains all of 'md', which makes it more
+                * suitable for this purpose.
                 */
-               if ((fh = fopen(DEVRANDOM, "r")) != NULL)
-                       {
-                       unsigned char tmpbuf[ENTROPY_NEEDED];
-                       int n;
 
-                       n=fread((unsigned char *)tmpbuf,1,ENTROPY_NEEDED,fh);
-                       fclose(fh);
-                       RAND_add(tmpbuf,sizeof tmpbuf,n);
-                       memset(tmpbuf,0,n);
-                       }
-#endif
-#ifdef PURIFY
-               memset(state,0,STATE_SIZE);
-               memset(md,0,MD_DIGEST_LENGTH);
+               int n = STATE_SIZE; /* so that the complete pool gets accessed */
+               while (n > 0)
+                       {
+#if MD_DIGEST_LENGTH > 20
+# error "Please adjust DUMMY_SEED."
 #endif
-               CRYPTO_w_lock(CRYPTO_LOCK_RAND);
-               init=0;
+#define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
+                       /* Note that the seed does not matter, it's just that
+                        * ssleay_rand_add expects to have something to hash. */
+                       ssleay_rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
+                       n -= MD_DIGEST_LENGTH;
+                       }
+               if (ok)
+                       stirred_pool = 1;
                }
 
-       ok = (entropy >= ENTROPY_NEEDED);
-
        st_idx=state_index;
        st_num=state_num;
        md_c[0] = md_count[0];
@@ -448,6 +571,8 @@ static int ssleay_rand_bytes(unsigned char *buf, int num)
        else
                {
                RANDerr(RAND_F_SSLEAY_RAND_BYTES,RAND_R_PRNG_NOT_SEEDED);
+               ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
+                       "http://www.openssl.org/support/faq.html");
                return(0);
                }
        }
@@ -469,100 +594,17 @@ static int ssleay_rand_pseudo_bytes(unsigned char *buf, int num)
        return (ret);
        }
 
-#ifdef WINDOWS
-#include <windows.h>
-#include <openssl/rand.h>
+static int ssleay_rand_status(void)
+       {
+       int ret;
 
-/*****************************************************************************
- * Initialisation function for the SSL random generator.  Takes the contents
- * of the screen as random seed.
- *
- * Created 960901 by Gertjan van Oosten, gertjan@West.NL, West Consulting B.V.
- *
- * Code adapted from
- * <URL:http://www.microsoft.com/kb/developr/win_dk/q97193.htm>;
- * the original copyright message is:
- *
- *   (C) Copyright Microsoft Corp. 1993.  All rights reserved.
- *
- *   You have a royalty-free right to use, modify, reproduce and
- *   distribute the Sample Files (and/or any modified version) in
- *   any way you find useful, provided that you agree that
- *   Microsoft has no warranty obligations or liability for any
- *   Sample Application Files which are modified.
- */
-/*
- * I have modified the loading of bytes via RAND_seed() mechanism since
- * the origional would have been very very CPU intensive since RAND_seed()
- * does an MD5 per 16 bytes of input.  The cost to digest 16 bytes is the same
- * as that to digest 56 bytes.  So under the old system, a screen of
- * 1024*768*256 would have been CPU cost of approximatly 49,000 56 byte MD5
- * digests or digesting 2.7 mbytes.  What I have put in place would
- * be 48 16k MD5 digests, or efectivly 48*16+48 MD5 bytes or 816 kbytes
- * or about 3.5 times as much.
- * - eric 
- */
-void RAND_screen(void)
-{
-  HDC          hScrDC;         /* screen DC */
-  HDC          hMemDC;         /* memory DC */
-  HBITMAP      hBitmap;        /* handle for our bitmap */
-  HBITMAP      hOldBitmap;     /* handle for previous bitmap */
-  BITMAP       bm;             /* bitmap properties */
-  unsigned int size;           /* size of bitmap */
-  char         *bmbits;        /* contents of bitmap */
-  int          w;              /* screen width */
-  int          h;              /* screen height */
-  int          y;              /* y-coordinate of screen lines to grab */
-  int          n = 16;         /* number of screen lines to grab at a time */
-
-  /* Create a screen DC and a memory DC compatible to screen DC */
-  hScrDC = CreateDC("DISPLAY", NULL, NULL, NULL);
-  hMemDC = CreateCompatibleDC(hScrDC);
-
-  /* Get screen resolution */
-  w = GetDeviceCaps(hScrDC, HORZRES);
-  h = GetDeviceCaps(hScrDC, VERTRES);
-
-  /* Create a bitmap compatible with the screen DC */
-  hBitmap = CreateCompatibleBitmap(hScrDC, w, n);
-
-  /* Select new bitmap into memory DC */
-  hOldBitmap = SelectObject(hMemDC, hBitmap);
-
-  /* Get bitmap properties */
-  GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&bm);
-  size = (unsigned int)bm.bmWidthBytes * bm.bmHeight * bm.bmPlanes;
-
-  bmbits = Malloc(size);
-  if (bmbits) {
-    /* Now go through the whole screen, repeatedly grabbing n lines */
-    for (y = 0; y < h-n; y += n)
-       {
-       unsigned char md[MD_DIGEST_LENGTH];
-
-       /* Bitblt screen DC to memory DC */
-       BitBlt(hMemDC, 0, 0, w, n, hScrDC, 0, y, SRCCOPY);
-
-       /* Copy bitmap bits from memory DC to bmbits */
-       GetBitmapBits(hBitmap, size, bmbits);
-
-       /* Get the MD5 of the bitmap */
-       MD(bmbits,size,md);
-
-       /* Seed the random generator with the MD5 digest */
-       RAND_seed(md, MD_DIGEST_LENGTH);
-       }
+       CRYPTO_w_lock(CRYPTO_LOCK_RAND);
 
-    Free(bmbits);
-  }
+       if (!initialized)
+               ssleay_rand_initialize();
+       ret = entropy >= ENTROPY_NEEDED;
 
-  /* Select old bitmap back into memory DC */
-  hBitmap = SelectObject(hMemDC, hOldBitmap);
+       CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
 
-  /* Clean up */
-  DeleteObject(hBitmap);
-  DeleteDC(hMemDC);
-  DeleteDC(hScrDC);
-}
-#endif
+       return ret;
+       }