2
0

rand_unix.c 25 KB

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