rand_unix.c 24 KB

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