Debian Codegraph @

random/rndoldlinux.c

raw
1 /* rndoldlinux.c - raw random number for OSes with /dev/random
2 * Copyright (C) 1998, 2001, 2002, 2003, 2007,
3 * 2009 Free Software Foundation, Inc.
4 *
5 * This file is part of Libgcrypt.
6 *
7 * Libgcrypt is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2.1 of
10 * the License, or (at your option) any later version.
11 *
12 * Libgcrypt is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
19 */
20
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <errno.h>
26 #include <sys/types.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <fcntl.h>
30 #include <poll.h>
31 #if defined(__APPLE__) && defined(__MACH__)
32 #include <Availability.h>
33 #ifdef __MAC_10_11
34 #include <TargetConditionals.h>
35 #if !defined(TARGET_OS_IPHONE) || TARGET_OS_IPHONE == 0
36 extern int getentropy (void *buf, size_t buflen) __attribute__ ((weak_import));
37 #define HAVE_GETENTROPY
38 #endif
39 #endif
40 #endif
41 #if defined(__linux__) || !defined(HAVE_GETENTROPY)
42 #ifdef HAVE_SYSCALL
43 # include <sys/syscall.h>
44 # ifdef __NR_getrandom
45 # define getentropy(buf,buflen) syscall (__NR_getrandom, buf, buflen, 0)
46 # endif
47 #endif
48 #endif
49
50 #include "types.h"
51 #include "g10lib.h"
52 #include "rand-internal.h"
53
54 static int open_device (const char *name, int retry);
55
56
57 static int
58 set_cloexec_flag (int fd)
59 {
60 int oldflags;
61
62 oldflags= fcntl (fd, F_GETFD, 0);
63 if (oldflags < 0)
64 return oldflags;
65 oldflags |= FD_CLOEXEC;
66 return fcntl (fd, F_SETFD, oldflags);
67 }
68
69
70
71 /*
72 * Used to open the /dev/random devices (Linux, xBSD, Solaris (if it
73 * exists)). If RETRY is true, the function does not terminate with
74 * a fatal error but retries until it is able to reopen the device.
75 */
76 static int
77 open_device (const char *name, int retry)
78 {
79 int fd;
80
81 if (retry)
82 _gcry_random_progress ("open_dev_random", 'X', 1, 0);
83 again:
84 fd = open (name, O_RDONLY);
85 if (fd == -1 && retry)
86 {
87 _gcry_random_progress ("wait_dev_random", 'X', 0, 5);
88 poll (NULL, 0, 5000);
89 goto again;
90 }
91 if (fd == -1)
92 log_fatal ("can't open %s: %s\n", name, strerror(errno) );
93
94 if (set_cloexec_flag (fd))
95 log_error ("error setting FD_CLOEXEC on fd %d: %s\n",
96 fd, strerror (errno));
97
98 /* We used to do the following check, however it turned out that this
99 is not portable since more OSes provide a random device which is
100 sometimes implemented as another device type.
101
102 struct stat sb;
103
104 if( fstat( fd, &sb ) )
105 log_fatal("stat() off %s failed: %s\n", name, strerror(errno) );
106 if( (!S_ISCHR(sb.st_mode)) && (!S_ISFIFO(sb.st_mode)) )
107 log_fatal("invalid random device!\n" );
108 */
109 return fd;
110 }
111
112
113 /* Note that the caller needs to make sure that this function is only
114 * called by one thread at a time. The function returns 0 on success
115 * or true on failure (in which case the caller will signal a fatal
116 * error). This function should be entered only by one thread at a
117 * time. */
118 int
119 _gcry_rndoldlinux_gather_random (void (*add)(const void*, size_t,
120 enum random_origins),
121 enum random_origins origin,
122 size_t length, int level )
123 {
124 static int fd_urandom = -1;
125 static int fd_random = -1;
126 static int only_urandom = -1;
127 static unsigned char ever_opened;
128 static volatile pid_t my_pid; /* The volatile is there to make sure
129 * the compiler does not optimize the
130 * code away in case the getpid
131 * function is badly attributed. */
132 volatile pid_t apid;
133 int fd;
134 int n;
135 byte buffer[768];
136 size_t n_hw;
137 size_t want = length;
138 size_t last_so_far = 0;
139 int any_need_entropy = 0;
140 int delay;
141
142 /* On the first call read the conf file to check whether we want to
143 * use only urandom. */
144 if (only_urandom == -1)
145 {
146 my_pid = getpid ();
147 if ((_gcry_random_read_conf () & RANDOM_CONF_ONLY_URANDOM))
148 only_urandom = 1;
149 else
150 only_urandom = 0;
151 }
152
153 if (!add)
154 {
155 /* Special mode to close the descriptors. */
156 if (fd_random != -1)
157 {
158 close (fd_random);
159 fd_random = -1;
160 }
161 if (fd_urandom != -1)
162 {
163 close (fd_urandom);
164 fd_urandom = -1;
165 }
166
167 _gcry_rndjent_fini ();
168 return 0;
169 }
170
171 /* Detect a fork and close the devices so that we don't use the old
172 * file descriptors. Note that open_device will be called in retry
173 * mode if the devices was opened by the parent process. */
174 apid = getpid ();
175 if (my_pid != apid)
176 {
177 if (fd_random != -1)
178 {
179 close (fd_random);
180 fd_random = -1;
181 }
182 if (fd_urandom != -1)
183 {
184 close (fd_urandom);
185 fd_urandom = -1;
186 }
187 my_pid = apid;
188 }
189
190
191 /* First read from a hardware source. Note that _gcry_rndhw_poll_slow lets
192 it account only for up to 50% (or 25% for RDRAND) of the requested
193 bytes. */
194 n_hw = _gcry_rndhw_poll_slow (add, origin, length);
195 if (length > 1)
196 length -= n_hw;
197
198 /* When using a blocking random generator try to get some entropy
199 * from the jitter based RNG. In this case we take up to 50% of the
200 * remaining requested bytes. */
201 if (level >= GCRY_VERY_STRONG_RANDOM)
202 {
203 n_hw = _gcry_rndjent_poll (add, origin, length/2);
204 if (n_hw > length/2)
205 n_hw = length/2;
206 if (length > 1)
207 length -= n_hw;
208 }
209
210
211 /* Open the requested device. The first time a device is to be
212 opened we fail with a fatal error if the device does not exists.
213 In case the device has ever been closed, further open requests
214 will however retry indefinitely. The rationale for this behaviour is
215 that we always require the device to be existent but want a more
216 graceful behaviour if the rarely needed close operation has been
217 used and the device needs to be re-opened later. */
218 if (level >= GCRY_VERY_STRONG_RANDOM && !only_urandom)
219 {
220 if (fd_random == -1)
221 {
222 fd_random = open_device (NAME_OF_DEV_RANDOM, (ever_opened & 1));
223 ever_opened |= 1;
224 }
225 fd = fd_random;
226 }
227 else
228 {
229 if (fd_urandom == -1)
230 {
231 fd_urandom = open_device (NAME_OF_DEV_URANDOM, (ever_opened & 2));
232 ever_opened |= 2;
233 }
234 fd = fd_urandom;
235 }
236
237 /* Enter the read loop. */
238 delay = 0; /* Start with 0 seconds so that we do no block on the
239 first iteration and in turn call the progress function
240 before blocking. To give the OS a better chance to
241 return with something we will actually use 100ms. */
242 while (length)
243 {
244 int rc;
245 struct pollfd pfd;
246
247 /* If we have a modern operating system, we first try to use the new
248 * getentropy function. That call guarantees that the kernel's
249 * RNG has been properly seeded before returning any data. This
250 * is different from /dev/urandom which may, due to its
251 * non-blocking semantics, return data even if the kernel has
252 * not been properly seeded. And it differs from /dev/random by never
253 * blocking once the kernel is seeded. */
254 #if defined(HAVE_GETENTROPY) || defined(__NR_getrandom)
255 #if defined(__APPLE__) && defined(__MACH__)
256 if (&getentropy != NULL)
257 #endif
258 {
259 long ret;
260 size_t nbytes;
261
262 do
263 {
264 nbytes = length < sizeof(buffer)? length : sizeof(buffer);
265 if (nbytes > 256)
266 nbytes = 256;
267 _gcry_pre_syscall ();
268 ret = getentropy (buffer, nbytes);
269 _gcry_post_syscall ();
270 }
271 while (ret == -1 && errno == EINTR);
272 if (ret == -1 && errno == ENOSYS)
273 ; /* getentropy is not supported - fallback to pulling from fd. */
274 else
275 { /* getentropy is supported. Some sanity checks. */
276 if (ret == -1)
277 log_fatal ("unexpected error from getentropy: %s\n",
278 strerror (errno));
279 #ifdef __NR_getrandom
280 else if (ret != nbytes)
281 log_fatal ("getentropy returned only"
282 " %ld of %zu requested bytes\n", ret, nbytes);
283 #endif
284
285 (*add)(buffer, nbytes, origin);
286 length -= nbytes;
287 continue; /* until LENGTH is zero. */
288 }
289 }
290 #endif
291
292 /* If we collected some bytes update the progress indicator. We
293 do this always and not just if the poll timed out because
294 often just a few bytes are gathered within the timeout
295 period. */
296 if (any_need_entropy || last_so_far != (want - length) )
297 {
298 last_so_far = want - length;
299 _gcry_random_progress ("need_entropy", 'X',
300 (int)last_so_far, (int)want);
301 any_need_entropy = 1;
302 }
303
304 pfd.fd = fd;
305 pfd.events = POLLIN;
306
307 _gcry_pre_syscall ();
308 rc = poll (&pfd, 1, delay);
309 _gcry_post_syscall ();
310 if (!rc)
311 {
312 any_need_entropy = 1;
313 delay = 3000; /* Use 3 seconds henceforth. */
314 continue;
315 }
316 else if( rc == -1 )
317 {
318 log_error ("poll() error: %s\n", strerror (errno));
319 if (!delay)
320 delay = 1000; /* Use 1 second if we encounter an error before
321 we have ever blocked. */
322 continue;
323 }
324
325 do
326 {
327 size_t nbytes;
328
329 nbytes = length < sizeof(buffer)? length : sizeof(buffer);
330 n = read (fd, buffer, nbytes);
331 if (n >= 0 && n > nbytes)
332 {
333 log_error("bogus read from random device (n=%d)\n", n );
334 n = nbytes;
335 }
336 }
337 while (n == -1 && errno == EINTR);
338 if (n == -1)
339 log_fatal("read error on random device: %s\n", strerror(errno));
340 (*add)(buffer, n, origin);
341 length -= n;
342 }
343 wipememory (buffer, sizeof buffer);
344
345 if (any_need_entropy)
346 _gcry_random_progress ("need_entropy", 'X', (int)want, (int)want);
347
348 return 0; /* success */
349 }