comparison dbrandom.c @ 858:220f55d540ae

rename random.h to dbrandom.h since some OSes have a system random.h
author Matt Johnston <matt@ucc.asn.au>
date Thu, 14 Nov 2013 22:05:47 +0800
parents random.c@c19acba28590
children a1e79ffa5862
comparison
equal deleted inserted replaced
857:c19acba28590 858:220f55d540ae
1 /*
2 * Dropbear - a SSH2 server
3 *
4 * Copyright (c) 2002,2003 Matt Johnston
5 * All rights reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE. */
24
25 #include "includes.h"
26 #include "buffer.h"
27 #include "dbutil.h"
28 #include "bignum.h"
29 #include "dbrandom.h"
30
31
32 /* this is used to generate unique output from the same hashpool */
33 static uint32_t counter = 0;
34 /* the max value for the counter, so it won't integer overflow */
35 #define MAX_COUNTER 1<<30
36
37 static unsigned char hashpool[SHA1_HASH_SIZE] = {0};
38 static int donerandinit = 0;
39
40 #define INIT_SEED_SIZE 32 /* 256 bits */
41
42 /* The basic setup is we read some data from /dev/(u)random or prngd and hash it
43 * into hashpool. To read data, we hash together current hashpool contents,
44 * and a counter. We feed more data in by hashing the current pool and new
45 * data into the pool.
46 *
47 * It is important to ensure that counter doesn't wrap around before we
48 * feed in new entropy.
49 *
50 */
51
52 /* Pass len=0 to hash an entire file */
53 static int
54 process_file(hash_state *hs, const char *filename,
55 unsigned int len, int prngd)
56 {
57 static int already_blocked = 0;
58 int readfd;
59 unsigned int readcount;
60 int ret = DROPBEAR_FAILURE;
61
62 #ifdef DROPBEAR_PRNGD_SOCKET
63 if (prngd)
64 {
65 readfd = connect_unix(filename);
66 }
67 else
68 #endif
69 {
70 readfd = open(filename, O_RDONLY);
71 }
72
73 if (readfd < 0) {
74 goto out;
75 }
76
77 readcount = 0;
78 while (len == 0 || readcount < len)
79 {
80 int readlen, wantread;
81 unsigned char readbuf[4096];
82 if (!already_blocked && !prngd)
83 {
84 int res;
85 struct timeval timeout;
86 fd_set read_fds;
87
88 timeout.tv_sec = 2;
89 timeout.tv_usec = 0;
90
91 FD_ZERO(&read_fds);
92 FD_SET(readfd, &read_fds);
93 res = select(readfd + 1, &read_fds, NULL, NULL, &timeout);
94 if (res == 0)
95 {
96 dropbear_log(LOG_WARNING, "Warning: Reading the randomness source '%s' seems to have blocked.\nYou may need to find a better entropy source.", filename);
97 already_blocked = 1;
98 }
99 }
100
101 if (len == 0)
102 {
103 wantread = sizeof(readbuf);
104 }
105 else
106 {
107 wantread = MIN(sizeof(readbuf), len-readcount);
108 }
109
110 #ifdef DROPBEAR_PRNGD_SOCKET
111 if (prngd)
112 {
113 char egdcmd[2];
114 egdcmd[0] = 0x02; /* blocking read */
115 egdcmd[1] = (unsigned char)wantread;
116 if (write(readfd, egdcmd, 2) < 0)
117 {
118 dropbear_exit("Can't send command to egd");
119 }
120 }
121 #endif
122
123 readlen = read(readfd, readbuf, wantread);
124 if (readlen <= 0) {
125 if (readlen < 0 && errno == EINTR) {
126 continue;
127 }
128 if (readlen == 0 && len == 0)
129 {
130 /* whole file was read as requested */
131 break;
132 }
133 goto out;
134 }
135 sha1_process(hs, readbuf, readlen);
136 readcount += readlen;
137 }
138 ret = DROPBEAR_SUCCESS;
139 out:
140 close(readfd);
141 return ret;
142 }
143
144 void addrandom(char * buf, unsigned int len)
145 {
146 hash_state hs;
147
148 /* hash in the new seed data */
149 sha1_init(&hs);
150 /* existing state (zeroes on startup) */
151 sha1_process(&hs, (void*)hashpool, sizeof(hashpool));
152
153 /* new */
154 sha1_process(&hs, buf, len);
155 sha1_done(&hs, hashpool);
156 }
157
158 static void write_urandom()
159 {
160 #ifndef DROPBEAR_PRNGD_SOCKET
161 /* This is opportunistic, don't worry about failure */
162 unsigned char buf[INIT_SEED_SIZE];
163 FILE *f = fopen(DROPBEAR_URANDOM_DEV, "w");
164 if (!f) {
165 return;
166 }
167 genrandom(buf, sizeof(buf));
168 fwrite(buf, sizeof(buf), 1, f);
169 fclose(f);
170 #endif
171 }
172
173 /* Initialise the prng from /dev/urandom or prngd. This function can
174 * be called multiple times */
175 void seedrandom() {
176
177 hash_state hs;
178
179 pid_t pid;
180 struct timeval tv;
181 clock_t clockval;
182
183 /* hash in the new seed data */
184 sha1_init(&hs);
185 /* existing state */
186 sha1_process(&hs, (void*)hashpool, sizeof(hashpool));
187
188 #ifdef DROPBEAR_PRNGD_SOCKET
189 if (process_file(&hs, DROPBEAR_PRNGD_SOCKET, INIT_SEED_SIZE, 1)
190 != DROPBEAR_SUCCESS) {
191 dropbear_exit("Failure reading random device %s",
192 DROPBEAR_PRNGD_SOCKET);
193 }
194 #else
195 /* non-blocking random source (probably /dev/urandom) */
196 if (process_file(&hs, DROPBEAR_URANDOM_DEV, INIT_SEED_SIZE, 0)
197 != DROPBEAR_SUCCESS) {
198 dropbear_exit("Failure reading random device %s",
199 DROPBEAR_URANDOM_DEV);
200 }
201 #endif
202
203 /* A few other sources to fall back on.
204 * Add more here for other platforms */
205 #ifdef __linux__
206 /* Seems to be a reasonable source of entropy from timers. Possibly hard
207 * for even local attackers to reproduce */
208 process_file(&hs, "/proc/timer_list", 0, 0);
209 /* Might help on systems with wireless */
210 process_file(&hs, "/proc/interrupts", 0, 0);
211
212 process_file(&hs, "/proc/loadavg", 0, 0);
213 process_file(&hs, "/proc/sys/kernel/random/entropy_avail", 0, 0);
214
215 /* Mostly network visible but useful in some situations.
216 * Limit size to avoid slowdowns on systems with lots of routes */
217 process_file(&hs, "/proc/net/netstat", 4096, 0);
218 process_file(&hs, "/proc/net/dev", 4096, 0);
219 process_file(&hs, "/proc/net/tcp", 4096, 0);
220 /* Also includes interface lo */
221 process_file(&hs, "/proc/net/rt_cache", 4096, 0);
222 process_file(&hs, "/proc/vmstat", 0, 0);
223 #endif
224
225 pid = getpid();
226 sha1_process(&hs, (void*)&pid, sizeof(pid));
227
228 /* gettimeofday() doesn't completely fill out struct timeval on
229 OS X (10.8.3), avoid valgrind warnings by clearing it first */
230 memset(&tv, 0x0, sizeof(tv));
231 gettimeofday(&tv, NULL);
232 sha1_process(&hs, (void*)&tv, sizeof(tv));
233
234 clockval = clock();
235 sha1_process(&hs, (void*)&clockval, sizeof(clockval));
236
237 /* When a private key is read by the client or server it will
238 * be added to the hashpool - see runopts.c */
239
240 sha1_done(&hs, hashpool);
241
242 counter = 0;
243 donerandinit = 1;
244
245 /* Feed it all back into /dev/urandom - this might help if Dropbear
246 * is running from inetd and gets new state each time */
247 write_urandom();
248 }
249
250 /* return len bytes of pseudo-random data */
251 void genrandom(unsigned char* buf, unsigned int len) {
252
253 hash_state hs;
254 unsigned char hash[SHA1_HASH_SIZE];
255 unsigned int copylen;
256
257 if (!donerandinit) {
258 dropbear_exit("seedrandom not done");
259 }
260
261 while (len > 0) {
262 sha1_init(&hs);
263 sha1_process(&hs, (void*)hashpool, sizeof(hashpool));
264 sha1_process(&hs, (void*)&counter, sizeof(counter));
265 sha1_done(&hs, hash);
266
267 counter++;
268 if (counter > MAX_COUNTER) {
269 seedrandom();
270 }
271
272 copylen = MIN(len, SHA1_HASH_SIZE);
273 memcpy(buf, hash, copylen);
274 len -= copylen;
275 buf += copylen;
276 }
277 m_burn(hash, sizeof(hash));
278 }
279
280 /* Generates a random mp_int.
281 * max is a *mp_int specifying an upper bound.
282 * rand must be an initialised *mp_int for the result.
283 * the result rand satisfies: 0 < rand < max
284 * */
285 void gen_random_mpint(mp_int *max, mp_int *rand) {
286
287 unsigned char *randbuf = NULL;
288 unsigned int len = 0;
289 const unsigned char masks[] = {0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f};
290
291 const int size_bits = mp_count_bits(max);
292
293 len = size_bits / 8;
294 if ((size_bits % 8) != 0) {
295 len += 1;
296 }
297
298 randbuf = (unsigned char*)m_malloc(len);
299 do {
300 genrandom(randbuf, len);
301 /* Mask out the unrequired bits - mp_read_unsigned_bin expects
302 * MSB first.*/
303 randbuf[0] &= masks[size_bits % 8];
304
305 bytes_to_mp(rand, randbuf, len);
306
307 /* keep regenerating until we get one satisfying
308 * 0 < rand < max */
309 } while (mp_cmp(rand, max) != MP_LT);
310 m_burn(randbuf, len);
311 m_free(randbuf);
312 }