|
Line 0
Link Here
|
|
|
1 |
/* |
| 2 |
* Copyright (c) 1996, David Mazieres <dm@uun.org> |
| 3 |
* Copyright (c) 2008, Damien Miller <djm@openbsd.org> |
| 4 |
* Copyright (c) 2013, Markus Friedl <markus@openbsd.org> |
| 5 |
* |
| 6 |
* Permission to use, copy, modify, and distribute this software for any |
| 7 |
* purpose with or without fee is hereby granted, provided that the above |
| 8 |
* copyright notice and this permission notice appear in all copies. |
| 9 |
* |
| 10 |
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |
| 11 |
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
| 12 |
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |
| 13 |
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
| 14 |
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
| 15 |
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |
| 16 |
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 17 |
*/ |
| 18 |
|
| 19 |
#include "includes.h" |
| 20 |
|
| 21 |
#ifndef HAVE_GETENTROPY |
| 22 |
|
| 23 |
#ifndef SSH_RANDOM_DEV |
| 24 |
# define SSH_RANDOM_DEV "/dev/urandom" |
| 25 |
#endif /* SSH_RANDOM_DEV */ |
| 26 |
|
| 27 |
#include <sys/types.h> |
| 28 |
#ifdef HAVE_SYS_RANDOM_H |
| 29 |
# include <sys/random.h> |
| 30 |
#endif |
| 31 |
|
| 32 |
#include <fcntl.h> |
| 33 |
#include <stdlib.h> |
| 34 |
#include <string.h> |
| 35 |
#include <unistd.h> |
| 36 |
#ifdef WITH_OPENSSL |
| 37 |
#include <openssl/rand.h> |
| 38 |
#include <openssl/err.h> |
| 39 |
#endif |
| 40 |
|
| 41 |
#include "log.h" |
| 42 |
|
| 43 |
int |
| 44 |
getentropy(void *s, size_t len) |
| 45 |
{ |
| 46 |
#ifdef WITH_OPENSSL |
| 47 |
if (RAND_bytes(s, len) <= 0) |
| 48 |
fatal("Couldn't obtain random bytes (error 0x%lx)", |
| 49 |
(unsigned long)ERR_get_error()); |
| 50 |
#else |
| 51 |
int fd, save_errno; |
| 52 |
ssize_t r; |
| 53 |
size_t o = 0; |
| 54 |
|
| 55 |
#ifdef HAVE_GETRANDOM |
| 56 |
if ((r = getrandom(s, len, 0)) > 0 && (size_t)r == len) |
| 57 |
return 0; |
| 58 |
#endif /* HAVE_GETRANDOM */ |
| 59 |
|
| 60 |
if ((fd = open(SSH_RANDOM_DEV, O_RDONLY)) == -1) { |
| 61 |
save_errno = errno; |
| 62 |
/* Try egd/prngd before giving up. */ |
| 63 |
if (seed_from_prngd(s, len) == 0) |
| 64 |
return 0; |
| 65 |
fatal("Couldn't open %s: %s", SSH_RANDOM_DEV, |
| 66 |
strerror(save_errno)); |
| 67 |
} |
| 68 |
while (o < len) { |
| 69 |
r = read(fd, (u_char *)s + o, len - o); |
| 70 |
if (r < 0) { |
| 71 |
if (errno == EAGAIN || errno == EINTR || |
| 72 |
errno == EWOULDBLOCK) |
| 73 |
continue; |
| 74 |
fatal("read %s: %s", SSH_RANDOM_DEV, strerror(errno)); |
| 75 |
} |
| 76 |
o += r; |
| 77 |
} |
| 78 |
close(fd); |
| 79 |
#endif /* WITH_OPENSSL */ |
| 80 |
return 0; |
| 81 |
} |
| 82 |
#endif /* WITH_GETENTROPY */ |