Fix overflow check in BN_bn2dec()
[openssl.git] / crypto / bn / bn_rand.c
index 48de9cb7cac2b0f06fc60df09a2c4a3ccec91e92..2266d22b66aa7a5506d4149e538efbca12b3b781 100644 (file)
@@ -121,6 +121,11 @@ static int bnrand(int pseudorand, BIGNUM *rnd, int bits, int top, int bottom)
     int ret = 0, bit, bytes, mask;
     time_t tim;
 
+    if (bits < 0 || (bits == 1 && top > 0)) {
+        BNerr(BN_F_BNRAND, BN_R_BITS_TOO_SMALL);
+        return 0;
+    }
+
     if (bits == 0) {
         BN_zero(rnd);
         return 1;
@@ -140,13 +145,9 @@ static int bnrand(int pseudorand, BIGNUM *rnd, int bits, int top, int bottom)
     time(&tim);
     RAND_add(&tim, sizeof(tim), 0.0);
 
-    if (pseudorand) {
-        if (RAND_pseudo_bytes(buf, bytes) == -1)
-            goto err;
-    } else {
-        if (RAND_bytes(buf, bytes) <= 0)
-            goto err;
-    }
+    /* We ignore the value of pseudorand and always call RAND_bytes */
+    if (RAND_bytes(buf, bytes) <= 0)
+        goto err;
 
 #if 1
     if (pseudorand == 2) {
@@ -157,7 +158,7 @@ static int bnrand(int pseudorand, BIGNUM *rnd, int bits, int top, int bottom)
         unsigned char c;
 
         for (i = 0; i < bytes; i++) {
-            if(RAND_pseudo_bytes(&c, 1) < 0)
+            if (RAND_pseudo_bytes(&c, 1) < 0)
                 goto err;
             if (c >= 128 && i > 0)
                 buf[i] = buf[i - 1];
@@ -169,7 +170,7 @@ static int bnrand(int pseudorand, BIGNUM *rnd, int bits, int top, int bottom)
     }
 #endif
 
-    if (top != -1) {
+    if (top >= 0) {
         if (top) {
             if (bit == 0) {
                 buf[0] = 1;