New function BN_bntest_rand() to detect more BN library bugs.
[openssl.git] / crypto / bn / bn_rand.c
index b567b43a6ff96ecd8b925b8a0d791f674db419dd..bab4510345090374089fd7d66d1313b88a29b6ed 100644 (file)
 #include "bn_lcl.h"
 #include <openssl/rand.h>
 
-int BN_rand(BIGNUM *rnd, int bits, int top, int bottom)
+static int bnrand(int pseudorand, BIGNUM *rnd, int bits, int top, int bottom)
        {
        unsigned char *buf=NULL;
        int ret=0,bit,bytes,mask;
        time_t tim;
 
+       if (bits == 0)
+               {
+               BN_zero(rnd);
+               return 1;
+               }
+
        bytes=(bits+7)/8;
        bit=(bits-1)%8;
        mask=0xff<<bit;
 
-       buf=(unsigned char *)Malloc(bytes);
+       buf=(unsigned char *)OPENSSL_malloc(bytes);
        if (buf == NULL)
                {
                BNerr(BN_F_BN_RAND,ERR_R_MALLOC_FAILURE);
@@ -83,8 +89,38 @@ int BN_rand(BIGNUM *rnd, int bits, int top, int bottom)
        time(&tim);
        RAND_add(&tim,sizeof(tim),0);
 
-       if (RAND_bytes(buf,(int)bytes) <= 0)
-               goto err;
+       if (pseudorand)
+               {
+               if (RAND_pseudo_bytes(buf, bytes) == -1)
+                       goto err;
+               }
+       else
+               {
+               if (RAND_bytes(buf, bytes) <= 0)
+                       goto err;
+               }
+
+#if 1
+       if (pseudorand == 2)
+               {
+               /* generate patterns that are more likely to trigger BN
+                  library bugs */
+               int i;
+               unsigned char c;
+
+               for (i = 0; i < bytes; i++)
+                       {
+                       RAND_pseudo_bytes(&c, 1);
+                       if (c >= 128 && i > 0)
+                               buf[i] = buf[i-1];
+                       else if (c < 42)
+                               buf[i] = 0;
+                       else if (c < 84)
+                               buf[i] = 255;
+                       }
+               }
+#endif
+
        if (top)
                {
                if (bit == 0)
@@ -111,8 +147,24 @@ err:
        if (buf != NULL)
                {
                memset(buf,0,bytes);
-               Free(buf);
+               OPENSSL_free(buf);
                }
        return(ret);
        }
 
+int     BN_rand(BIGNUM *rnd, int bits, int top, int bottom)
+       {
+       return bnrand(0, rnd, bits, top, bottom);
+       }
+
+int     BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom)
+       {
+       return bnrand(1, rnd, bits, top, bottom);
+       }
+
+#if 1
+int     BN_bntest_rand(BIGNUM *rnd, int bits, int top, int bottom)
+       {
+       return bnrand(2, rnd, bits, top, bottom);
+       }
+#endif