Clean up RAND_bytes() calls
[openssl.git] / crypto / bn / bn_rand.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <time.h>
12 #include "internal/cryptlib.h"
13 #include "bn_lcl.h"
14 #include <openssl/rand.h>
15 #include <openssl/sha.h>
16
17 static int bnrand(int pseudorand, BIGNUM *rnd, int bits, int top, int bottom)
18 {
19     unsigned char *buf = NULL;
20     int ret = 0, bit, bytes, mask;
21     time_t tim;
22
23     if (bits < 0 || (bits == 1 && top > 0)) {
24         BNerr(BN_F_BNRAND, BN_R_BITS_TOO_SMALL);
25         return 0;
26     }
27
28     if (bits == 0) {
29         BN_zero(rnd);
30         return 1;
31     }
32
33     bytes = (bits + 7) / 8;
34     bit = (bits - 1) % 8;
35     mask = 0xff << (bit + 1);
36
37     buf = OPENSSL_malloc(bytes);
38     if (buf == NULL) {
39         BNerr(BN_F_BNRAND, ERR_R_MALLOC_FAILURE);
40         goto err;
41     }
42
43     /* make a random number and set the top and bottom bits */
44     time(&tim);
45     RAND_add(&tim, sizeof(tim), 0.0);
46
47     if (RAND_bytes(buf, bytes) <= 0)
48         goto err;
49
50     if (pseudorand == 2) {
51         /*
52          * generate patterns that are more likely to trigger BN library bugs
53          */
54         int i;
55         unsigned char c;
56
57         for (i = 0; i < bytes; i++) {
58             if (RAND_bytes(&c, 1) <= 0)
59                 goto err;
60             if (c >= 128 && i > 0)
61                 buf[i] = buf[i - 1];
62             else if (c < 42)
63                 buf[i] = 0;
64             else if (c < 84)
65                 buf[i] = 255;
66         }
67     }
68
69     if (top >= 0) {
70         if (top) {
71             if (bit == 0) {
72                 buf[0] = 1;
73                 buf[1] |= 0x80;
74             } else {
75                 buf[0] |= (3 << (bit - 1));
76             }
77         } else {
78             buf[0] |= (1 << bit);
79         }
80     }
81     buf[0] &= ~mask;
82     if (bottom)                 /* set bottom bit if requested */
83         buf[bytes - 1] |= 1;
84     if (!BN_bin2bn(buf, bytes, rnd))
85         goto err;
86     ret = 1;
87  err:
88     OPENSSL_clear_free(buf, bytes);
89     bn_check_top(rnd);
90     return (ret);
91 }
92
93 int BN_rand(BIGNUM *rnd, int bits, int top, int bottom)
94 {
95     return bnrand(0, rnd, bits, top, bottom);
96 }
97
98 int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom)
99 {
100     return bnrand(1, rnd, bits, top, bottom);
101 }
102
103 int BN_bntest_rand(BIGNUM *rnd, int bits, int top, int bottom)
104 {
105     return bnrand(2, rnd, bits, top, bottom);
106 }
107
108 /* random number r:  0 <= r < range */
109 static int bn_rand_range(int pseudo, BIGNUM *r, const BIGNUM *range)
110 {
111     int (*bn_rand) (BIGNUM *, int, int, int) =
112         pseudo ? BN_pseudo_rand : BN_rand;
113     int n;
114     int count = 100;
115
116     if (range->neg || BN_is_zero(range)) {
117         BNerr(BN_F_BN_RAND_RANGE, BN_R_INVALID_RANGE);
118         return 0;
119     }
120
121     n = BN_num_bits(range);     /* n > 0 */
122
123     /* BN_is_bit_set(range, n - 1) always holds */
124
125     if (n == 1)
126         BN_zero(r);
127     else if (!BN_is_bit_set(range, n - 2) && !BN_is_bit_set(range, n - 3)) {
128         /*
129          * range = 100..._2, so 3*range (= 11..._2) is exactly one bit longer
130          * than range
131          */
132         do {
133             if (!bn_rand(r, n + 1, -1, 0))
134                 return 0;
135             /*
136              * If r < 3*range, use r := r MOD range (which is either r, r -
137              * range, or r - 2*range). Otherwise, iterate once more. Since
138              * 3*range = 11..._2, each iteration succeeds with probability >=
139              * .75.
140              */
141             if (BN_cmp(r, range) >= 0) {
142                 if (!BN_sub(r, r, range))
143                     return 0;
144                 if (BN_cmp(r, range) >= 0)
145                     if (!BN_sub(r, r, range))
146                         return 0;
147             }
148
149             if (!--count) {
150                 BNerr(BN_F_BN_RAND_RANGE, BN_R_TOO_MANY_ITERATIONS);
151                 return 0;
152             }
153
154         }
155         while (BN_cmp(r, range) >= 0);
156     } else {
157         do {
158             /* range = 11..._2  or  range = 101..._2 */
159             if (!bn_rand(r, n, -1, 0))
160                 return 0;
161
162             if (!--count) {
163                 BNerr(BN_F_BN_RAND_RANGE, BN_R_TOO_MANY_ITERATIONS);
164                 return 0;
165             }
166         }
167         while (BN_cmp(r, range) >= 0);
168     }
169
170     bn_check_top(r);
171     return 1;
172 }
173
174 int BN_rand_range(BIGNUM *r, const BIGNUM *range)
175 {
176     return bn_rand_range(0, r, range);
177 }
178
179 int BN_pseudo_rand_range(BIGNUM *r, const BIGNUM *range)
180 {
181     return bn_rand_range(1, r, range);
182 }
183
184 /*
185  * BN_generate_dsa_nonce generates a random number 0 <= out < range. Unlike
186  * BN_rand_range, it also includes the contents of |priv| and |message| in
187  * the generation so that an RNG failure isn't fatal as long as |priv|
188  * remains secret. This is intended for use in DSA and ECDSA where an RNG
189  * weakness leads directly to private key exposure unless this function is
190  * used.
191  */
192 int BN_generate_dsa_nonce(BIGNUM *out, const BIGNUM *range,
193                           const BIGNUM *priv, const unsigned char *message,
194                           size_t message_len, BN_CTX *ctx)
195 {
196     SHA512_CTX sha;
197     /*
198      * We use 512 bits of random data per iteration to ensure that we have at
199      * least |range| bits of randomness.
200      */
201     unsigned char random_bytes[64];
202     unsigned char digest[SHA512_DIGEST_LENGTH];
203     unsigned done, todo;
204     /* We generate |range|+8 bytes of random output. */
205     const unsigned num_k_bytes = BN_num_bytes(range) + 8;
206     unsigned char private_bytes[96];
207     unsigned char *k_bytes;
208     int ret = 0;
209
210     k_bytes = OPENSSL_malloc(num_k_bytes);
211     if (k_bytes == NULL)
212         goto err;
213
214     /* We copy |priv| into a local buffer to avoid exposing its length. */
215     todo = sizeof(priv->d[0]) * priv->top;
216     if (todo > sizeof(private_bytes)) {
217         /*
218          * No reasonable DSA or ECDSA key should have a private key this
219          * large and we don't handle this case in order to avoid leaking the
220          * length of the private key.
221          */
222         BNerr(BN_F_BN_GENERATE_DSA_NONCE, BN_R_PRIVATE_KEY_TOO_LARGE);
223         goto err;
224     }
225     memcpy(private_bytes, priv->d, todo);
226     memset(private_bytes + todo, 0, sizeof(private_bytes) - todo);
227
228     for (done = 0; done < num_k_bytes;) {
229         if (RAND_bytes(random_bytes, sizeof(random_bytes)) != 1)
230             goto err;
231         SHA512_Init(&sha);
232         SHA512_Update(&sha, &done, sizeof(done));
233         SHA512_Update(&sha, private_bytes, sizeof(private_bytes));
234         SHA512_Update(&sha, message, message_len);
235         SHA512_Update(&sha, random_bytes, sizeof(random_bytes));
236         SHA512_Final(digest, &sha);
237
238         todo = num_k_bytes - done;
239         if (todo > SHA512_DIGEST_LENGTH)
240             todo = SHA512_DIGEST_LENGTH;
241         memcpy(k_bytes + done, digest, todo);
242         done += todo;
243     }
244
245     if (!BN_bin2bn(k_bytes, num_k_bytes, out))
246         goto err;
247     if (BN_mod(out, out, range, ctx) != 1)
248         goto err;
249     ret = 1;
250
251  err:
252     OPENSSL_free(k_bytes);
253     return ret;
254 }