rand_unix.c 24 KB

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