rand_unix.c 25 KB

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