rand_unix.c 24 KB

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