dropbar: Update to version 2013.60.1.
[tomato.git] / release / src / router / dropbear / random.c
blob76ff81a2a1548f4ef3e75ed6cf1a8cb4c940cbf8
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:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
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. */
25 #include "includes.h"
26 #include "buffer.h"
27 #include "dbutil.h"
28 #include "bignum.h"
29 #include "random.h"
31 /* this is used to generate unique output from the same hashpool */
32 static uint32_t counter = 0;
33 /* the max value for the counter, so it won't integer overflow */
34 #define MAX_COUNTER 1<<30
36 static unsigned char hashpool[SHA1_HASH_SIZE] = {0};
37 static int donerandinit = 0;
39 #define INIT_SEED_SIZE 32 /* 256 bits */
41 /* The basic setup is we read some data from /dev/(u)random or prngd and hash it
42 * into hashpool. To read data, we hash together current hashpool contents,
43 * and a counter. We feed more data in by hashing the current pool and new
44 * data into the pool.
46 * It is important to ensure that counter doesn't wrap around before we
47 * feed in new entropy.
51 /* Pass len=0 to hash an entire file */
52 static int
53 process_file(hash_state *hs, const char *filename,
54 unsigned int len, int prngd)
56 static int already_blocked = 0;
57 int readfd;
58 unsigned int readcount;
59 int ret = DROPBEAR_FAILURE;
61 #ifdef DROPBEAR_PRNGD_SOCKET
62 if (prngd)
64 readfd = connect_unix(filename);
66 else
67 #endif
69 readfd = open(filename, O_RDONLY);
72 if (readfd < 0) {
73 goto out;
76 readcount = 0;
77 while (len == 0 || readcount < len)
79 int readlen, wantread;
80 unsigned char readbuf[4096];
81 if (!already_blocked)
83 int ret;
84 struct timeval timeout = { .tv_sec = 2, .tv_usec = 0};
85 fd_set read_fds;
87 FD_ZERO(&read_fds);
88 FD_SET(readfd, &read_fds);
89 ret = select(readfd + 1, &read_fds, NULL, NULL, &timeout);
90 if (ret == 0)
92 dropbear_log(LOG_WARNING, "Warning: Reading the randomness source '%s' seems to have blocked.\nYou may need to find a better entropy source.", filename);
93 already_blocked = 1;
97 if (len == 0)
99 wantread = sizeof(readbuf);
101 else
103 wantread = MIN(sizeof(readbuf), len-readcount);
106 #ifdef DROPBEAR_PRNGD_SOCKET
107 if (prngd)
109 char egdcmd[2];
110 egdcmd[0] = 0x02; /* blocking read */
111 egdcmd[1] = (unsigned char)wantread;
112 if (write(readfd, egdcmd, 2) < 0)
114 dropbear_exit("Can't send command to egd");
117 #endif
119 readlen = read(readfd, readbuf, wantread);
120 if (readlen <= 0) {
121 if (readlen < 0 && errno == EINTR) {
122 continue;
124 if (readlen == 0 && len == 0)
126 /* whole file was read as requested */
127 break;
129 goto out;
131 sha1_process(hs, readbuf, readlen);
132 readcount += readlen;
134 ret = DROPBEAR_SUCCESS;
135 out:
136 close(readfd);
137 return ret;
140 void addrandom(char * buf, unsigned int len)
142 hash_state hs;
144 /* hash in the new seed data */
145 sha1_init(&hs);
146 /* existing state (zeroes on startup) */
147 sha1_process(&hs, (void*)hashpool, sizeof(hashpool));
149 /* new */
150 sha1_process(&hs, buf, len);
151 sha1_done(&hs, hashpool);
154 static void write_urandom()
156 #ifndef DROPBEAR_PRNGD_SOCKET
157 /* This is opportunistic, don't worry about failure */
158 unsigned char buf[INIT_SEED_SIZE];
159 FILE *f = fopen(DROPBEAR_URANDOM_DEV, "w");
160 if (!f) {
161 return;
163 genrandom(buf, sizeof(buf));
164 fwrite(buf, sizeof(buf), 1, f);
165 fclose(f);
166 #endif
169 /* Initialise the prng from /dev/urandom or prngd. This function can
170 * be called multiple times */
171 void seedrandom() {
173 hash_state hs;
175 pid_t pid;
176 struct timeval tv;
177 clock_t clockval;
179 /* hash in the new seed data */
180 sha1_init(&hs);
181 /* existing state */
182 sha1_process(&hs, (void*)hashpool, sizeof(hashpool));
184 #ifdef DROPBEAR_PRNGD_SOCKET
185 if (process_file(&hs, DROPBEAR_PRNGD_SOCKET, INIT_SEED_SIZE, 1)
186 != DROPBEAR_SUCCESS) {
187 dropbear_exit("Failure reading random device %s",
188 DROPBEAR_PRNGD_SOCKET);
190 #else
191 /* non-blocking random source (probably /dev/urandom) */
192 if (process_file(&hs, DROPBEAR_URANDOM_DEV, INIT_SEED_SIZE, 0)
193 != DROPBEAR_SUCCESS) {
194 dropbear_exit("Failure reading random device %s",
195 DROPBEAR_URANDOM_DEV);
197 #endif
199 /* A few other sources to fall back on.
200 * Add more here for other platforms */
201 #ifdef __linux__
202 /* Seems to be a reasonable source of entropy from timers. Possibly hard
203 * for even local attackers to reproduce */
204 process_file(&hs, "/proc/timer_list", 0, 0);
205 /* Might help on systems with wireless */
206 process_file(&hs, "/proc/interrupts", 0, 0);
208 process_file(&hs, "/proc/loadavg", 0, 0);
209 process_file(&hs, "/proc/sys/kernel/random/entropy_avail", 0, 0);
211 /* Mostly network visible but useful in some situations.
212 * Limit size to avoid slowdowns on systems with lots of routes */
213 process_file(&hs, "/proc/net/netstat", 4096, 0);
214 process_file(&hs, "/proc/net/dev", 4096, 0);
215 process_file(&hs, "/proc/net/tcp", 4096, 0);
216 /* Also includes interface lo */
217 process_file(&hs, "/proc/net/rt_cache", 4096, 0);
218 process_file(&hs, "/proc/vmstat", 0, 0);
219 #endif
221 pid = getpid();
222 sha1_process(&hs, (void*)&pid, sizeof(pid));
224 // gettimeofday() doesn't completely fill out struct timeval on
225 // OS X (10.8.3), avoid valgrind warnings by clearing it first
226 memset(&tv, 0x0, sizeof(tv));
227 gettimeofday(&tv, NULL);
228 sha1_process(&hs, (void*)&tv, sizeof(tv));
230 clockval = clock();
231 sha1_process(&hs, (void*)&clockval, sizeof(clockval));
233 /* When a private key is read by the client or server it will
234 * be added to the hashpool - see runopts.c */
236 sha1_done(&hs, hashpool);
238 counter = 0;
239 donerandinit = 1;
241 /* Feed it all back into /dev/urandom - this might help if Dropbear
242 * is running from inetd and gets new state each time */
243 write_urandom();
246 /* return len bytes of pseudo-random data */
247 void genrandom(unsigned char* buf, unsigned int len) {
249 hash_state hs;
250 unsigned char hash[SHA1_HASH_SIZE];
251 unsigned int copylen;
253 if (!donerandinit) {
254 dropbear_exit("seedrandom not done");
257 while (len > 0) {
258 sha1_init(&hs);
259 sha1_process(&hs, (void*)hashpool, sizeof(hashpool));
260 sha1_process(&hs, (void*)&counter, sizeof(counter));
261 sha1_done(&hs, hash);
263 counter++;
264 if (counter > MAX_COUNTER) {
265 seedrandom();
268 copylen = MIN(len, SHA1_HASH_SIZE);
269 memcpy(buf, hash, copylen);
270 len -= copylen;
271 buf += copylen;
273 m_burn(hash, sizeof(hash));
276 /* Generates a random mp_int.
277 * max is a *mp_int specifying an upper bound.
278 * rand must be an initialised *mp_int for the result.
279 * the result rand satisfies: 0 < rand < max
280 * */
281 void gen_random_mpint(mp_int *max, mp_int *rand) {
283 unsigned char *randbuf = NULL;
284 unsigned int len = 0;
285 const unsigned char masks[] = {0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f};
287 const int size_bits = mp_count_bits(max);
289 len = size_bits / 8;
290 if ((size_bits % 8) != 0) {
291 len += 1;
294 randbuf = (unsigned char*)m_malloc(len);
295 do {
296 genrandom(randbuf, len);
297 /* Mask out the unrequired bits - mp_read_unsigned_bin expects
298 * MSB first.*/
299 randbuf[0] &= masks[size_bits % 8];
301 bytes_to_mp(rand, randbuf, len);
303 /* keep regenerating until we get one satisfying
304 * 0 < rand < max */
305 } while (mp_cmp(rand, max) != MP_LT);
306 m_burn(randbuf, len);
307 m_free(randbuf);