rand_unix.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. /*
  2. * Copyright 1995-2019 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. #ifndef _GNU_SOURCE
  10. # define _GNU_SOURCE
  11. #endif
  12. #include "e_os.h"
  13. #include <stdio.h>
  14. #include "internal/cryptlib.h"
  15. #include <openssl/rand.h>
  16. #include <openssl/crypto.h>
  17. #include "rand_lcl.h"
  18. #include "internal/rand_int.h"
  19. #include <stdio.h>
  20. #include "internal/dso.h"
  21. #ifdef __linux
  22. # include <sys/syscall.h>
  23. # ifdef DEVRANDOM_WAIT
  24. # include <sys/shm.h>
  25. # include <sys/utsname.h>
  26. # endif
  27. #endif
  28. #if defined(__FreeBSD__) && !defined(OPENSSL_SYS_UEFI)
  29. # include <sys/types.h>
  30. # include <sys/sysctl.h>
  31. # include <sys/param.h>
  32. #endif
  33. #if defined(__OpenBSD__) || defined(__NetBSD__)
  34. # include <sys/param.h>
  35. #endif
  36. #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
  37. # include <sys/types.h>
  38. # include <sys/stat.h>
  39. # include <fcntl.h>
  40. # include <unistd.h>
  41. # include <sys/time.h>
  42. static uint64_t get_time_stamp(void);
  43. static uint64_t get_timer_bits(void);
  44. /* Macro to convert two thirty two bit values into a sixty four bit one */
  45. # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
  46. /*
  47. * Check for the existence and support of POSIX timers. The standard
  48. * says that the _POSIX_TIMERS macro will have a positive value if they
  49. * are available.
  50. *
  51. * However, we want an additional constraint: that the timer support does
  52. * not require an extra library dependency. Early versions of glibc
  53. * require -lrt to be specified on the link line to access the timers,
  54. * so this needs to be checked for.
  55. *
  56. * It is worse because some libraries define __GLIBC__ but don't
  57. * support the version testing macro (e.g. uClibc). This means
  58. * an extra check is needed.
  59. *
  60. * The final condition is:
  61. * "have posix timers and either not glibc or glibc without -lrt"
  62. *
  63. * The nested #if sequences are required to avoid using a parameterised
  64. * macro that might be undefined.
  65. */
  66. # undef OSSL_POSIX_TIMER_OKAY
  67. # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
  68. # if defined(__GLIBC__)
  69. # if defined(__GLIBC_PREREQ)
  70. # if __GLIBC_PREREQ(2, 17)
  71. # define OSSL_POSIX_TIMER_OKAY
  72. # endif
  73. # endif
  74. # else
  75. # define OSSL_POSIX_TIMER_OKAY
  76. # endif
  77. # endif
  78. #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */
  79. #if defined(OPENSSL_RAND_SEED_NONE)
  80. /* none means none. this simplifies the following logic */
  81. # undef OPENSSL_RAND_SEED_OS
  82. # undef OPENSSL_RAND_SEED_GETRANDOM
  83. # undef OPENSSL_RAND_SEED_LIBRANDOM
  84. # undef OPENSSL_RAND_SEED_DEVRANDOM
  85. # undef OPENSSL_RAND_SEED_RDTSC
  86. # undef OPENSSL_RAND_SEED_RDCPU
  87. # undef OPENSSL_RAND_SEED_EGD
  88. #endif
  89. #if (defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)) && \
  90. !defined(OPENSSL_RAND_SEED_NONE)
  91. # error "UEFI and VXWorks only support seeding NONE"
  92. #endif
  93. #if defined(OPENSSL_SYS_VXWORKS)
  94. /* empty implementation */
  95. int rand_pool_init(void)
  96. {
  97. return 1;
  98. }
  99. void rand_pool_cleanup(void)
  100. {
  101. }
  102. void rand_pool_keep_random_devices_open(int keep)
  103. {
  104. }
  105. size_t rand_pool_acquire_entropy(RAND_POOL *pool)
  106. {
  107. return rand_pool_entropy_available(pool);
  108. }
  109. #endif
  110. #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
  111. || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
  112. || defined(OPENSSL_SYS_UEFI))
  113. # if defined(OPENSSL_SYS_VOS)
  114. # ifndef OPENSSL_RAND_SEED_OS
  115. # error "Unsupported seeding method configured; must be os"
  116. # endif
  117. # if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
  118. # error "Unsupported HP-PA and IA32 at the same time."
  119. # endif
  120. # if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
  121. # error "Must have one of HP-PA or IA32"
  122. # endif
  123. /*
  124. * The following algorithm repeatedly samples the real-time clock (RTC) to
  125. * generate a sequence of unpredictable data. The algorithm relies upon the
  126. * uneven execution speed of the code (due to factors such as cache misses,
  127. * interrupts, bus activity, and scheduling) and upon the rather large
  128. * relative difference between the speed of the clock and the rate at which
  129. * it can be read. If it is ported to an environment where execution speed
  130. * is more constant or where the RTC ticks at a much slower rate, or the
  131. * clock can be read with fewer instructions, it is likely that the results
  132. * would be far more predictable. This should only be used for legacy
  133. * platforms.
  134. *
  135. * As a precaution, we assume only 2 bits of entropy per byte.
  136. */
  137. size_t rand_pool_acquire_entropy(RAND_POOL *pool)
  138. {
  139. short int code;
  140. int i, k;
  141. size_t bytes_needed;
  142. struct timespec ts;
  143. unsigned char v;
  144. # ifdef OPENSSL_SYS_VOS_HPPA
  145. long duration;
  146. extern void s$sleep(long *_duration, short int *_code);
  147. # else
  148. long long duration;
  149. extern void s$sleep2(long long *_duration, short int *_code);
  150. # endif
  151. bytes_needed = rand_pool_bytes_needed(pool, 4 /*entropy_factor*/);
  152. for (i = 0; i < bytes_needed; i++) {
  153. /*
  154. * burn some cpu; hope for interrupts, cache collisions, bus
  155. * interference, etc.
  156. */
  157. for (k = 0; k < 99; k++)
  158. ts.tv_nsec = random();
  159. # ifdef OPENSSL_SYS_VOS_HPPA
  160. /* sleep for 1/1024 of a second (976 us). */
  161. duration = 1;
  162. s$sleep(&duration, &code);
  163. # else
  164. /* sleep for 1/65536 of a second (15 us). */
  165. duration = 1;
  166. s$sleep2(&duration, &code);
  167. # endif
  168. /* Get wall clock time, take 8 bits. */
  169. clock_gettime(CLOCK_REALTIME, &ts);
  170. v = (unsigned char)(ts.tv_nsec & 0xFF);
  171. rand_pool_add(pool, arg, &v, sizeof(v) , 2);
  172. }
  173. return rand_pool_entropy_available(pool);
  174. }
  175. void rand_pool_cleanup(void)
  176. {
  177. }
  178. void rand_pool_keep_random_devices_open(int keep)
  179. {
  180. }
  181. # else
  182. # if defined(OPENSSL_RAND_SEED_EGD) && \
  183. (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
  184. # error "Seeding uses EGD but EGD is turned off or no device given"
  185. # endif
  186. # if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
  187. # error "Seeding uses urandom but DEVRANDOM is not configured"
  188. # endif
  189. # if defined(OPENSSL_RAND_SEED_OS)
  190. # if !defined(DEVRANDOM)
  191. # error "OS seeding requires DEVRANDOM to be configured"
  192. # endif
  193. # define OPENSSL_RAND_SEED_GETRANDOM
  194. # define OPENSSL_RAND_SEED_DEVRANDOM
  195. # endif
  196. # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
  197. # error "librandom not (yet) supported"
  198. # endif
  199. # if (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
  200. /*
  201. * sysctl_random(): Use sysctl() to read a random number from the kernel
  202. * Returns the number of bytes returned in buf on success, -1 on failure.
  203. */
  204. static ssize_t sysctl_random(char *buf, size_t buflen)
  205. {
  206. int mib[2];
  207. size_t done = 0;
  208. size_t len;
  209. /*
  210. * Note: sign conversion between size_t and ssize_t is safe even
  211. * without a range check, see comment in syscall_random()
  212. */
  213. /*
  214. * On FreeBSD old implementations returned longs, newer versions support
  215. * variable sizes up to 256 byte. The code below would not work properly
  216. * when the sysctl returns long and we want to request something not a
  217. * multiple of longs, which should never be the case.
  218. */
  219. if (!ossl_assert(buflen % sizeof(long) == 0)) {
  220. errno = EINVAL;
  221. return -1;
  222. }
  223. /*
  224. * On NetBSD before 4.0 KERN_ARND was an alias for KERN_URND, and only
  225. * filled in an int, leaving the rest uninitialized. Since NetBSD 4.0
  226. * it returns a variable number of bytes with the current version supporting
  227. * up to 256 bytes.
  228. * Just return an error on older NetBSD versions.
  229. */
  230. #if defined(__NetBSD__) && __NetBSD_Version__ < 400000000
  231. errno = ENOSYS;
  232. return -1;
  233. #endif
  234. mib[0] = CTL_KERN;
  235. mib[1] = KERN_ARND;
  236. do {
  237. len = buflen;
  238. if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
  239. return done > 0 ? done : -1;
  240. done += len;
  241. buf += len;
  242. buflen -= len;
  243. } while (buflen > 0);
  244. return done;
  245. }
  246. # endif
  247. # if defined(OPENSSL_RAND_SEED_GETRANDOM)
  248. # if defined(__linux) && !defined(__NR_getrandom)
  249. # if defined(__arm__) && defined(__NR_SYSCALL_BASE)
  250. # define __NR_getrandom (__NR_SYSCALL_BASE+384)
  251. # elif defined(__i386__)
  252. # define __NR_getrandom 355
  253. # elif defined(__x86_64__) && !defined(__ILP32__)
  254. # define __NR_getrandom 318
  255. # endif
  256. # endif
  257. /*
  258. * syscall_random(): Try to get random data using a system call
  259. * returns the number of bytes returned in buf, or < 0 on error.
  260. */
  261. static ssize_t syscall_random(void *buf, size_t buflen)
  262. {
  263. /*
  264. * Note: 'buflen' equals the size of the buffer which is used by the
  265. * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
  266. *
  267. * 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
  268. *
  269. * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
  270. * between size_t and ssize_t is safe even without a range check.
  271. */
  272. /*
  273. * Do runtime detection to find getentropy().
  274. *
  275. * Known OSs that should support this:
  276. * - Darwin since 16 (OSX 10.12, IOS 10.0).
  277. * - Solaris since 11.3
  278. * - OpenBSD since 5.6
  279. * - Linux since 3.17 with glibc 2.25
  280. * - FreeBSD since 12.0 (1200061)
  281. */
  282. # if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
  283. extern int getentropy(void *buffer, size_t length) __attribute__((weak));
  284. if (getentropy != NULL)
  285. return getentropy(buf, buflen) == 0 ? (ssize_t)buflen : -1;
  286. # else
  287. union {
  288. void *p;
  289. int (*f)(void *buffer, size_t length);
  290. } p_getentropy;
  291. /*
  292. * We could cache the result of the lookup, but we normally don't
  293. * call this function often.
  294. */
  295. ERR_set_mark();
  296. p_getentropy.p = DSO_global_lookup("getentropy");
  297. ERR_pop_to_mark();
  298. if (p_getentropy.p != NULL)
  299. return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
  300. # endif
  301. /* Linux supports this since version 3.17 */
  302. # if defined(__linux) && defined(__NR_getrandom)
  303. return syscall(__NR_getrandom, buf, buflen, 0);
  304. # elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
  305. return sysctl_random(buf, buflen);
  306. # else
  307. errno = ENOSYS;
  308. return -1;
  309. # endif
  310. }
  311. # endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
  312. # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
  313. static const char *random_device_paths[] = { DEVRANDOM };
  314. static struct random_device {
  315. int fd;
  316. dev_t dev;
  317. ino_t ino;
  318. mode_t mode;
  319. dev_t rdev;
  320. } random_devices[OSSL_NELEM(random_device_paths)];
  321. static int keep_random_devices_open = 1;
  322. # if defined(__linux) && defined(DEVRANDOM_WAIT)
  323. static void *shm_addr;
  324. static void cleanup_shm(void)
  325. {
  326. shmdt(shm_addr);
  327. }
  328. /*
  329. * Ensure that the system randomness source has been adequately seeded.
  330. * This is done by having the first start of libcrypto, wait until the device
  331. * /dev/random becomes able to supply a byte of entropy. Subsequent starts
  332. * of the library and later reseedings do not need to do this.
  333. */
  334. static int wait_random_seeded(void)
  335. {
  336. static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0;
  337. static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL };
  338. int kernel[2];
  339. int shm_id, fd, r;
  340. char c, *p;
  341. struct utsname un;
  342. fd_set fds;
  343. if (!seeded) {
  344. /* See if anything has created the global seeded indication */
  345. if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) {
  346. /*
  347. * Check the kernel's version and fail if it is too recent.
  348. *
  349. * Linux kernels from 4.8 onwards do not guarantee that
  350. * /dev/urandom is properly seeded when /dev/random becomes
  351. * readable. However, such kernels support the getentropy(2)
  352. * system call and this should always succeed which renders
  353. * this alternative but essentially identical source moot.
  354. */
  355. if (uname(&un) == 0) {
  356. kernel[0] = atoi(un.release);
  357. p = strchr(un.release, '.');
  358. kernel[1] = p == NULL ? 0 : atoi(p + 1);
  359. if (kernel[0] > kernel_version[0]
  360. || (kernel[0] == kernel_version[0]
  361. && kernel[1] >= kernel_version[1])) {
  362. return 0;
  363. }
  364. }
  365. /* Open /dev/random and wait for it to be readable */
  366. if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) {
  367. if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) {
  368. FD_ZERO(&fds);
  369. FD_SET(fd, &fds);
  370. while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0
  371. && errno == EINTR);
  372. } else {
  373. while ((r = read(fd, &c, 1)) < 0 && errno == EINTR);
  374. }
  375. close(fd);
  376. if (r == 1) {
  377. seeded = 1;
  378. /* Create the shared memory indicator */
  379. shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1,
  380. IPC_CREAT | S_IRUSR | S_IRGRP | S_IROTH);
  381. }
  382. }
  383. }
  384. if (shm_id != -1) {
  385. seeded = 1;
  386. /*
  387. * Map the shared memory to prevent its premature destruction.
  388. * If this call fails, it isn't a big problem.
  389. */
  390. shm_addr = shmat(shm_id, NULL, SHM_RDONLY);
  391. if (shm_addr != (void *)-1)
  392. OPENSSL_atexit(&cleanup_shm);
  393. }
  394. }
  395. return seeded;
  396. }
  397. # else /* defined __linux */
  398. static int wait_random_seeded(void)
  399. {
  400. return 1;
  401. }
  402. # endif
  403. /*
  404. * Verify that the file descriptor associated with the random source is
  405. * still valid. The rationale for doing this is the fact that it is not
  406. * uncommon for daemons to close all open file handles when daemonizing.
  407. * So the handle might have been closed or even reused for opening
  408. * another file.
  409. */
  410. static int check_random_device(struct random_device * rd)
  411. {
  412. struct stat st;
  413. return rd->fd != -1
  414. && fstat(rd->fd, &st) != -1
  415. && rd->dev == st.st_dev
  416. && rd->ino == st.st_ino
  417. && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
  418. && rd->rdev == st.st_rdev;
  419. }
  420. /*
  421. * Open a random device if required and return its file descriptor or -1 on error
  422. */
  423. static int get_random_device(size_t n)
  424. {
  425. struct stat st;
  426. struct random_device * rd = &random_devices[n];
  427. /* reuse existing file descriptor if it is (still) valid */
  428. if (check_random_device(rd))
  429. return rd->fd;
  430. /* open the random device ... */
  431. if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
  432. return rd->fd;
  433. /* ... and cache its relevant stat(2) data */
  434. if (fstat(rd->fd, &st) != -1) {
  435. rd->dev = st.st_dev;
  436. rd->ino = st.st_ino;
  437. rd->mode = st.st_mode;
  438. rd->rdev = st.st_rdev;
  439. } else {
  440. close(rd->fd);
  441. rd->fd = -1;
  442. }
  443. return rd->fd;
  444. }
  445. /*
  446. * Close a random device making sure it is a random device
  447. */
  448. static void close_random_device(size_t n)
  449. {
  450. struct random_device * rd = &random_devices[n];
  451. if (check_random_device(rd))
  452. close(rd->fd);
  453. rd->fd = -1;
  454. }
  455. int rand_pool_init(void)
  456. {
  457. size_t i;
  458. for (i = 0; i < OSSL_NELEM(random_devices); i++)
  459. random_devices[i].fd = -1;
  460. return 1;
  461. }
  462. void rand_pool_cleanup(void)
  463. {
  464. size_t i;
  465. for (i = 0; i < OSSL_NELEM(random_devices); i++)
  466. close_random_device(i);
  467. }
  468. void rand_pool_keep_random_devices_open(int keep)
  469. {
  470. if (!keep)
  471. rand_pool_cleanup();
  472. keep_random_devices_open = keep;
  473. }
  474. # else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
  475. int rand_pool_init(void)
  476. {
  477. return 1;
  478. }
  479. void rand_pool_cleanup(void)
  480. {
  481. }
  482. void rand_pool_keep_random_devices_open(int keep)
  483. {
  484. }
  485. # endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
  486. /*
  487. * Try the various seeding methods in turn, exit when successful.
  488. *
  489. * TODO(DRBG): If more than one entropy source is available, is it
  490. * preferable to stop as soon as enough entropy has been collected
  491. * (as favored by @rsalz) or should one rather be defensive and add
  492. * more entropy than requested and/or from different sources?
  493. *
  494. * Currently, the user can select multiple entropy sources in the
  495. * configure step, yet in practice only the first available source
  496. * will be used. A more flexible solution has been requested, but
  497. * currently it is not clear how this can be achieved without
  498. * overengineering the problem. There are many parameters which
  499. * could be taken into account when selecting the order and amount
  500. * of input from the different entropy sources (trust, quality,
  501. * possibility of blocking).
  502. */
  503. size_t rand_pool_acquire_entropy(RAND_POOL *pool)
  504. {
  505. # if defined(OPENSSL_RAND_SEED_NONE)
  506. return rand_pool_entropy_available(pool);
  507. # else
  508. size_t entropy_available;
  509. # if defined(OPENSSL_RAND_SEED_GETRANDOM)
  510. {
  511. size_t bytes_needed;
  512. unsigned char *buffer;
  513. ssize_t bytes;
  514. /* Maximum allowed number of consecutive unsuccessful attempts */
  515. int attempts = 3;
  516. bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
  517. while (bytes_needed != 0 && attempts-- > 0) {
  518. buffer = rand_pool_add_begin(pool, bytes_needed);
  519. bytes = syscall_random(buffer, bytes_needed);
  520. if (bytes > 0) {
  521. rand_pool_add_end(pool, bytes, 8 * bytes);
  522. bytes_needed -= bytes;
  523. attempts = 3; /* reset counter after successful attempt */
  524. } else if (bytes < 0 && errno != EINTR) {
  525. break;
  526. }
  527. }
  528. }
  529. entropy_available = rand_pool_entropy_available(pool);
  530. if (entropy_available > 0)
  531. return entropy_available;
  532. # endif
  533. # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
  534. {
  535. /* Not yet implemented. */
  536. }
  537. # endif
  538. # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
  539. if (wait_random_seeded()) {
  540. size_t bytes_needed;
  541. unsigned char *buffer;
  542. size_t i;
  543. bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
  544. for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
  545. i++) {
  546. ssize_t bytes = 0;
  547. /* Maximum number of consecutive unsuccessful attempts */
  548. int attempts = 3;
  549. const int fd = get_random_device(i);
  550. if (fd == -1)
  551. continue;
  552. while (bytes_needed != 0 && attempts-- > 0) {
  553. buffer = rand_pool_add_begin(pool, bytes_needed);
  554. bytes = read(fd, buffer, bytes_needed);
  555. if (bytes > 0) {
  556. rand_pool_add_end(pool, bytes, 8 * bytes);
  557. bytes_needed -= bytes;
  558. attempts = 3; /* reset counter on successful attempt */
  559. } else if (bytes < 0 && errno != EINTR) {
  560. break;
  561. }
  562. }
  563. if (bytes < 0 || !keep_random_devices_open)
  564. close_random_device(i);
  565. bytes_needed = rand_pool_bytes_needed(pool, 1);
  566. }
  567. entropy_available = rand_pool_entropy_available(pool);
  568. if (entropy_available > 0)
  569. return entropy_available;
  570. }
  571. # endif
  572. # if defined(OPENSSL_RAND_SEED_RDTSC)
  573. entropy_available = rand_acquire_entropy_from_tsc(pool);
  574. if (entropy_available > 0)
  575. return entropy_available;
  576. # endif
  577. # if defined(OPENSSL_RAND_SEED_RDCPU)
  578. entropy_available = rand_acquire_entropy_from_cpu(pool);
  579. if (entropy_available > 0)
  580. return entropy_available;
  581. # endif
  582. # if defined(OPENSSL_RAND_SEED_EGD)
  583. {
  584. static const char *paths[] = { DEVRANDOM_EGD, NULL };
  585. size_t bytes_needed;
  586. unsigned char *buffer;
  587. int i;
  588. bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
  589. for (i = 0; bytes_needed > 0 && paths[i] != NULL; i++) {
  590. size_t bytes = 0;
  591. int num;
  592. buffer = rand_pool_add_begin(pool, bytes_needed);
  593. num = RAND_query_egd_bytes(paths[i],
  594. buffer, (int)bytes_needed);
  595. if (num == (int)bytes_needed)
  596. bytes = bytes_needed;
  597. rand_pool_add_end(pool, bytes, 8 * bytes);
  598. bytes_needed = rand_pool_bytes_needed(pool, 1);
  599. }
  600. entropy_available = rand_pool_entropy_available(pool);
  601. if (entropy_available > 0)
  602. return entropy_available;
  603. }
  604. # endif
  605. return rand_pool_entropy_available(pool);
  606. # endif
  607. }
  608. # endif
  609. #endif
  610. #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
  611. int rand_pool_add_nonce_data(RAND_POOL *pool)
  612. {
  613. struct {
  614. pid_t pid;
  615. CRYPTO_THREAD_ID tid;
  616. uint64_t time;
  617. } data = { 0 };
  618. /*
  619. * Add process id, thread id, and a high resolution timestamp to
  620. * ensure that the nonce is unique with high probability for
  621. * different process instances.
  622. */
  623. data.pid = getpid();
  624. data.tid = CRYPTO_THREAD_get_current_id();
  625. data.time = get_time_stamp();
  626. return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
  627. }
  628. int rand_pool_add_additional_data(RAND_POOL *pool)
  629. {
  630. struct {
  631. int fork_id;
  632. CRYPTO_THREAD_ID tid;
  633. uint64_t time;
  634. } data = { 0 };
  635. /*
  636. * Add some noise from the thread id and a high resolution timer.
  637. * The fork_id adds some extra fork-safety.
  638. * The thread id adds a little randomness if the drbg is accessed
  639. * concurrently (which is the case for the <master> drbg).
  640. */
  641. data.fork_id = openssl_get_fork_id();
  642. data.tid = CRYPTO_THREAD_get_current_id();
  643. data.time = get_timer_bits();
  644. return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
  645. }
  646. /*
  647. * Get the current time with the highest possible resolution
  648. *
  649. * The time stamp is added to the nonce, so it is optimized for not repeating.
  650. * The current time is ideal for this purpose, provided the computer's clock
  651. * is synchronized.
  652. */
  653. static uint64_t get_time_stamp(void)
  654. {
  655. # if defined(OSSL_POSIX_TIMER_OKAY)
  656. {
  657. struct timespec ts;
  658. if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
  659. return TWO32TO64(ts.tv_sec, ts.tv_nsec);
  660. }
  661. # endif
  662. # if defined(__unix__) \
  663. || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
  664. {
  665. struct timeval tv;
  666. if (gettimeofday(&tv, NULL) == 0)
  667. return TWO32TO64(tv.tv_sec, tv.tv_usec);
  668. }
  669. # endif
  670. return time(NULL);
  671. }
  672. /*
  673. * Get an arbitrary timer value of the highest possible resolution
  674. *
  675. * The timer value is added as random noise to the additional data,
  676. * which is not considered a trusted entropy sourec, so any result
  677. * is acceptable.
  678. */
  679. static uint64_t get_timer_bits(void)
  680. {
  681. uint64_t res = OPENSSL_rdtsc();
  682. if (res != 0)
  683. return res;
  684. # if defined(__sun) || defined(__hpux)
  685. return gethrtime();
  686. # elif defined(_AIX)
  687. {
  688. timebasestruct_t t;
  689. read_wall_time(&t, TIMEBASE_SZ);
  690. return TWO32TO64(t.tb_high, t.tb_low);
  691. }
  692. # elif defined(OSSL_POSIX_TIMER_OKAY)
  693. {
  694. struct timespec ts;
  695. # ifdef CLOCK_BOOTTIME
  696. # define CLOCK_TYPE CLOCK_BOOTTIME
  697. # elif defined(_POSIX_MONOTONIC_CLOCK)
  698. # define CLOCK_TYPE CLOCK_MONOTONIC
  699. # else
  700. # define CLOCK_TYPE CLOCK_REALTIME
  701. # endif
  702. if (clock_gettime(CLOCK_TYPE, &ts) == 0)
  703. return TWO32TO64(ts.tv_sec, ts.tv_nsec);
  704. }
  705. # endif
  706. # if defined(__unix__) \
  707. || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
  708. {
  709. struct timeval tv;
  710. if (gettimeofday(&tv, NULL) == 0)
  711. return TWO32TO64(tv.tv_sec, tv.tv_usec);
  712. }
  713. # endif
  714. return time(NULL);
  715. }
  716. #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */