rand_unix.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. /*
  2. * Copyright 1995-2022 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 "prov/seeding.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(__DragonFly__)
  37. # include <sys/param.h>
  38. # include <sys/random.h>
  39. #endif
  40. #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
  41. || defined(__DJGPP__)
  42. # include <sys/types.h>
  43. # include <sys/stat.h>
  44. # include <fcntl.h>
  45. # include <unistd.h>
  46. # include <sys/time.h>
  47. static uint64_t get_time_stamp(void);
  48. static uint64_t get_timer_bits(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. # elif defined(__aarch64__)
  290. # define __NR_getrandom 278
  291. # else /* generic */
  292. # define __NR_getrandom 278
  293. # endif
  294. # endif
  295. /*
  296. * syscall_random(): Try to get random data using a system call
  297. * returns the number of bytes returned in buf, or < 0 on error.
  298. */
  299. static ssize_t syscall_random(void *buf, size_t buflen)
  300. {
  301. /*
  302. * Note: 'buflen' equals the size of the buffer which is used by the
  303. * get_entropy() callback of the RAND_DRBG. It is roughly bounded by
  304. *
  305. * 2 * RAND_POOL_FACTOR * (RAND_DRBG_STRENGTH / 8) = 2^14
  306. *
  307. * which is way below the OSSL_SSIZE_MAX limit. Therefore sign conversion
  308. * between size_t and ssize_t is safe even without a range check.
  309. */
  310. /*
  311. * Do runtime detection to find getentropy().
  312. *
  313. * Known OSs that should support this:
  314. * - Darwin since 16 (OSX 10.12, IOS 10.0).
  315. * - Solaris since 11.3
  316. * - OpenBSD since 5.6
  317. * - Linux since 3.17 with glibc 2.25
  318. * - FreeBSD since 12.0 (1200061)
  319. *
  320. * Note: Sometimes getentropy() can be provided but not implemented
  321. * internally. So we need to check errno for ENOSYS
  322. */
  323. # if !defined(__DragonFly__) && !defined(__NetBSD__)
  324. # if defined(__GNUC__) && __GNUC__>=2 && defined(__ELF__) && !defined(__hpux)
  325. extern int getentropy(void *buffer, size_t length) __attribute__((weak));
  326. if (getentropy != NULL) {
  327. if (getentropy(buf, buflen) == 0)
  328. return (ssize_t)buflen;
  329. if (errno != ENOSYS)
  330. return -1;
  331. }
  332. # elif defined(OPENSSL_APPLE_CRYPTO_RANDOM)
  333. if (CCRandomGenerateBytes(buf, buflen) == kCCSuccess)
  334. return (ssize_t)buflen;
  335. return -1;
  336. # else
  337. union {
  338. void *p;
  339. int (*f)(void *buffer, size_t length);
  340. } p_getentropy;
  341. /*
  342. * We could cache the result of the lookup, but we normally don't
  343. * call this function often.
  344. */
  345. ERR_set_mark();
  346. p_getentropy.p = DSO_global_lookup("getentropy");
  347. ERR_pop_to_mark();
  348. if (p_getentropy.p != NULL)
  349. return p_getentropy.f(buf, buflen) == 0 ? (ssize_t)buflen : -1;
  350. # endif
  351. # endif /* !__DragonFly__ */
  352. /* Linux supports this since version 3.17 */
  353. # if defined(__linux) && defined(__NR_getrandom)
  354. return syscall(__NR_getrandom, buf, buflen, 0);
  355. # elif (defined(__FreeBSD__) || defined(__NetBSD__)) && defined(KERN_ARND)
  356. return sysctl_random(buf, buflen);
  357. # elif (defined(__DragonFly__) && __DragonFly_version >= 500700) \
  358. || (defined(__NetBSD__) && __NetBSD_Version >= 1000000000)
  359. return getrandom(buf, buflen, 0);
  360. # else
  361. errno = ENOSYS;
  362. return -1;
  363. # endif
  364. }
  365. # endif /* defined(OPENSSL_RAND_SEED_GETRANDOM) */
  366. # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
  367. static const char *random_device_paths[] = { DEVRANDOM };
  368. static struct random_device {
  369. int fd;
  370. dev_t dev;
  371. ino_t ino;
  372. mode_t mode;
  373. dev_t rdev;
  374. } random_devices[OSSL_NELEM(random_device_paths)];
  375. static int keep_random_devices_open = 1;
  376. # if defined(__linux) && defined(DEVRANDOM_WAIT) \
  377. && defined(OPENSSL_RAND_SEED_GETRANDOM)
  378. static void *shm_addr;
  379. static void cleanup_shm(void)
  380. {
  381. shmdt(shm_addr);
  382. }
  383. /*
  384. * Ensure that the system randomness source has been adequately seeded.
  385. * This is done by having the first start of libcrypto, wait until the device
  386. * /dev/random becomes able to supply a byte of entropy. Subsequent starts
  387. * of the library and later reseedings do not need to do this.
  388. */
  389. static int wait_random_seeded(void)
  390. {
  391. static int seeded = OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID < 0;
  392. static const int kernel_version[] = { DEVRANDOM_SAFE_KERNEL };
  393. int kernel[2];
  394. int shm_id, fd, r;
  395. char c, *p;
  396. struct utsname un;
  397. fd_set fds;
  398. if (!seeded) {
  399. /* See if anything has created the global seeded indication */
  400. if ((shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1, 0)) == -1) {
  401. /*
  402. * Check the kernel's version and fail if it is too recent.
  403. *
  404. * Linux kernels from 4.8 onwards do not guarantee that
  405. * /dev/urandom is properly seeded when /dev/random becomes
  406. * readable. However, such kernels support the getentropy(2)
  407. * system call and this should always succeed which renders
  408. * this alternative but essentially identical source moot.
  409. */
  410. if (uname(&un) == 0) {
  411. kernel[0] = atoi(un.release);
  412. p = strchr(un.release, '.');
  413. kernel[1] = p == NULL ? 0 : atoi(p + 1);
  414. if (kernel[0] > kernel_version[0]
  415. || (kernel[0] == kernel_version[0]
  416. && kernel[1] >= kernel_version[1])) {
  417. return 0;
  418. }
  419. }
  420. /* Open /dev/random and wait for it to be readable */
  421. if ((fd = open(DEVRANDOM_WAIT, O_RDONLY)) != -1) {
  422. if (DEVRANDM_WAIT_USE_SELECT && fd < FD_SETSIZE) {
  423. FD_ZERO(&fds);
  424. FD_SET(fd, &fds);
  425. while ((r = select(fd + 1, &fds, NULL, NULL, NULL)) < 0
  426. && errno == EINTR);
  427. } else {
  428. while ((r = read(fd, &c, 1)) < 0 && errno == EINTR);
  429. }
  430. close(fd);
  431. if (r == 1) {
  432. seeded = 1;
  433. /* Create the shared memory indicator */
  434. shm_id = shmget(OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID, 1,
  435. IPC_CREAT | S_IRUSR | S_IRGRP | S_IROTH);
  436. }
  437. }
  438. }
  439. if (shm_id != -1) {
  440. seeded = 1;
  441. /*
  442. * Map the shared memory to prevent its premature destruction.
  443. * If this call fails, it isn't a big problem.
  444. */
  445. shm_addr = shmat(shm_id, NULL, SHM_RDONLY);
  446. if (shm_addr != (void *)-1)
  447. OPENSSL_atexit(&cleanup_shm);
  448. }
  449. }
  450. return seeded;
  451. }
  452. # else /* defined __linux && DEVRANDOM_WAIT && OPENSSL_RAND_SEED_GETRANDOM */
  453. static int wait_random_seeded(void)
  454. {
  455. return 1;
  456. }
  457. # endif
  458. /*
  459. * Verify that the file descriptor associated with the random source is
  460. * still valid. The rationale for doing this is the fact that it is not
  461. * uncommon for daemons to close all open file handles when daemonizing.
  462. * So the handle might have been closed or even reused for opening
  463. * another file.
  464. */
  465. static int check_random_device(struct random_device * rd)
  466. {
  467. struct stat st;
  468. return rd->fd != -1
  469. && fstat(rd->fd, &st) != -1
  470. && rd->dev == st.st_dev
  471. && rd->ino == st.st_ino
  472. && ((rd->mode ^ st.st_mode) & ~(S_IRWXU | S_IRWXG | S_IRWXO)) == 0
  473. && rd->rdev == st.st_rdev;
  474. }
  475. /*
  476. * Open a random device if required and return its file descriptor or -1 on error
  477. */
  478. static int get_random_device(size_t n)
  479. {
  480. struct stat st;
  481. struct random_device * rd = &random_devices[n];
  482. /* reuse existing file descriptor if it is (still) valid */
  483. if (check_random_device(rd))
  484. return rd->fd;
  485. /* open the random device ... */
  486. if ((rd->fd = open(random_device_paths[n], O_RDONLY)) == -1)
  487. return rd->fd;
  488. /* ... and cache its relevant stat(2) data */
  489. if (fstat(rd->fd, &st) != -1) {
  490. rd->dev = st.st_dev;
  491. rd->ino = st.st_ino;
  492. rd->mode = st.st_mode;
  493. rd->rdev = st.st_rdev;
  494. } else {
  495. close(rd->fd);
  496. rd->fd = -1;
  497. }
  498. return rd->fd;
  499. }
  500. /*
  501. * Close a random device making sure it is a random device
  502. */
  503. static void close_random_device(size_t n)
  504. {
  505. struct random_device * rd = &random_devices[n];
  506. if (check_random_device(rd))
  507. close(rd->fd);
  508. rd->fd = -1;
  509. }
  510. int ossl_rand_pool_init(void)
  511. {
  512. size_t i;
  513. for (i = 0; i < OSSL_NELEM(random_devices); i++)
  514. random_devices[i].fd = -1;
  515. return 1;
  516. }
  517. void ossl_rand_pool_cleanup(void)
  518. {
  519. size_t i;
  520. for (i = 0; i < OSSL_NELEM(random_devices); i++)
  521. close_random_device(i);
  522. }
  523. void ossl_rand_pool_keep_random_devices_open(int keep)
  524. {
  525. if (!keep)
  526. ossl_rand_pool_cleanup();
  527. keep_random_devices_open = keep;
  528. }
  529. # else /* !defined(OPENSSL_RAND_SEED_DEVRANDOM) */
  530. int ossl_rand_pool_init(void)
  531. {
  532. return 1;
  533. }
  534. void ossl_rand_pool_cleanup(void)
  535. {
  536. }
  537. void ossl_rand_pool_keep_random_devices_open(int keep)
  538. {
  539. }
  540. # endif /* defined(OPENSSL_RAND_SEED_DEVRANDOM) */
  541. /*
  542. * Try the various seeding methods in turn, exit when successful.
  543. *
  544. * If more than one entropy source is available, is it
  545. * preferable to stop as soon as enough entropy has been collected
  546. * (as favored by @rsalz) or should one rather be defensive and add
  547. * more entropy than requested and/or from different sources?
  548. *
  549. * Currently, the user can select multiple entropy sources in the
  550. * configure step, yet in practice only the first available source
  551. * will be used. A more flexible solution has been requested, but
  552. * currently it is not clear how this can be achieved without
  553. * overengineering the problem. There are many parameters which
  554. * could be taken into account when selecting the order and amount
  555. * of input from the different entropy sources (trust, quality,
  556. * possibility of blocking).
  557. */
  558. size_t ossl_pool_acquire_entropy(RAND_POOL *pool)
  559. {
  560. # if defined(OPENSSL_RAND_SEED_NONE)
  561. return ossl_rand_pool_entropy_available(pool);
  562. # else
  563. size_t entropy_available = 0;
  564. (void)entropy_available; /* avoid compiler warning */
  565. # if defined(OPENSSL_RAND_SEED_GETRANDOM)
  566. {
  567. size_t bytes_needed;
  568. unsigned char *buffer;
  569. ssize_t bytes;
  570. /* Maximum allowed number of consecutive unsuccessful attempts */
  571. int attempts = 3;
  572. bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
  573. while (bytes_needed != 0 && attempts-- > 0) {
  574. buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
  575. bytes = syscall_random(buffer, bytes_needed);
  576. if (bytes > 0) {
  577. ossl_rand_pool_add_end(pool, bytes, 8 * bytes);
  578. bytes_needed -= bytes;
  579. attempts = 3; /* reset counter after successful attempt */
  580. } else if (bytes < 0 && errno != EINTR) {
  581. break;
  582. }
  583. }
  584. }
  585. entropy_available = ossl_rand_pool_entropy_available(pool);
  586. if (entropy_available > 0)
  587. return entropy_available;
  588. # endif
  589. # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
  590. {
  591. /* Not yet implemented. */
  592. }
  593. # endif
  594. # if defined(OPENSSL_RAND_SEED_DEVRANDOM)
  595. if (wait_random_seeded()) {
  596. size_t bytes_needed;
  597. unsigned char *buffer;
  598. size_t i;
  599. bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
  600. for (i = 0; bytes_needed > 0 && i < OSSL_NELEM(random_device_paths);
  601. i++) {
  602. ssize_t bytes = 0;
  603. /* Maximum number of consecutive unsuccessful attempts */
  604. int attempts = 3;
  605. const int fd = get_random_device(i);
  606. if (fd == -1)
  607. continue;
  608. while (bytes_needed != 0 && attempts-- > 0) {
  609. buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
  610. bytes = read(fd, buffer, bytes_needed);
  611. if (bytes > 0) {
  612. ossl_rand_pool_add_end(pool, bytes, 8 * bytes);
  613. bytes_needed -= bytes;
  614. attempts = 3; /* reset counter on successful attempt */
  615. } else if (bytes < 0 && errno != EINTR) {
  616. break;
  617. }
  618. }
  619. if (bytes < 0 || !keep_random_devices_open)
  620. close_random_device(i);
  621. bytes_needed = ossl_rand_pool_bytes_needed(pool, 1);
  622. }
  623. entropy_available = ossl_rand_pool_entropy_available(pool);
  624. if (entropy_available > 0)
  625. return entropy_available;
  626. }
  627. # endif
  628. # if defined(OPENSSL_RAND_SEED_RDTSC)
  629. entropy_available = ossl_prov_acquire_entropy_from_tsc(pool);
  630. if (entropy_available > 0)
  631. return entropy_available;
  632. # endif
  633. # if defined(OPENSSL_RAND_SEED_RDCPU)
  634. entropy_available = ossl_prov_acquire_entropy_from_cpu(pool);
  635. if (entropy_available > 0)
  636. return entropy_available;
  637. # endif
  638. # if defined(OPENSSL_RAND_SEED_EGD)
  639. {
  640. static const char *paths[] = { DEVRANDOM_EGD, NULL };
  641. size_t bytes_needed;
  642. unsigned char *buffer;
  643. int i;
  644. bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
  645. for (i = 0; bytes_needed > 0 && paths[i] != NULL; i++) {
  646. size_t bytes = 0;
  647. int num;
  648. buffer = ossl_rand_pool_add_begin(pool, bytes_needed);
  649. num = RAND_query_egd_bytes(paths[i],
  650. buffer, (int)bytes_needed);
  651. if (num == (int)bytes_needed)
  652. bytes = bytes_needed;
  653. ossl_rand_pool_add_end(pool, bytes, 8 * bytes);
  654. bytes_needed = ossl_rand_pool_bytes_needed(pool, 1);
  655. }
  656. entropy_available = ossl_rand_pool_entropy_available(pool);
  657. if (entropy_available > 0)
  658. return entropy_available;
  659. }
  660. # endif
  661. return ossl_rand_pool_entropy_available(pool);
  662. # endif
  663. }
  664. # endif
  665. #endif
  666. #if (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS)) \
  667. || defined(__DJGPP__)
  668. int ossl_pool_add_nonce_data(RAND_POOL *pool)
  669. {
  670. struct {
  671. pid_t pid;
  672. CRYPTO_THREAD_ID tid;
  673. uint64_t time;
  674. } data;
  675. /* Erase the entire structure including any padding */
  676. memset(&data, 0, sizeof(data));
  677. /*
  678. * Add process id, thread id, and a high resolution timestamp to
  679. * ensure that the nonce is unique with high probability for
  680. * different process instances.
  681. */
  682. data.pid = getpid();
  683. data.tid = CRYPTO_THREAD_get_current_id();
  684. data.time = get_time_stamp();
  685. return ossl_rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
  686. }
  687. int ossl_rand_pool_add_additional_data(RAND_POOL *pool)
  688. {
  689. struct {
  690. int fork_id;
  691. CRYPTO_THREAD_ID tid;
  692. uint64_t time;
  693. } data;
  694. /* Erase the entire structure including any padding */
  695. memset(&data, 0, sizeof(data));
  696. /*
  697. * Add some noise from the thread id and a high resolution timer.
  698. * The fork_id adds some extra fork-safety.
  699. * The thread id adds a little randomness if the drbg is accessed
  700. * concurrently (which is the case for the <master> drbg).
  701. */
  702. data.fork_id = openssl_get_fork_id();
  703. data.tid = CRYPTO_THREAD_get_current_id();
  704. data.time = get_timer_bits();
  705. return ossl_rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
  706. }
  707. /*
  708. * Get the current time with the highest possible resolution
  709. *
  710. * The time stamp is added to the nonce, so it is optimized for not repeating.
  711. * The current time is ideal for this purpose, provided the computer's clock
  712. * is synchronized.
  713. */
  714. static uint64_t get_time_stamp(void)
  715. {
  716. # if defined(OSSL_POSIX_TIMER_OKAY)
  717. {
  718. struct timespec ts;
  719. if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
  720. return TWO32TO64(ts.tv_sec, ts.tv_nsec);
  721. }
  722. # endif
  723. # if defined(__unix__) \
  724. || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
  725. {
  726. struct timeval tv;
  727. if (gettimeofday(&tv, NULL) == 0)
  728. return TWO32TO64(tv.tv_sec, tv.tv_usec);
  729. }
  730. # endif
  731. return time(NULL);
  732. }
  733. /*
  734. * Get an arbitrary timer value of the highest possible resolution
  735. *
  736. * The timer value is added as random noise to the additional data,
  737. * which is not considered a trusted entropy sourec, so any result
  738. * is acceptable.
  739. */
  740. static uint64_t get_timer_bits(void)
  741. {
  742. uint64_t res = OPENSSL_rdtsc();
  743. if (res != 0)
  744. return res;
  745. # if defined(__sun) || defined(__hpux)
  746. return gethrtime();
  747. # elif defined(_AIX)
  748. {
  749. timebasestruct_t t;
  750. read_wall_time(&t, TIMEBASE_SZ);
  751. return TWO32TO64(t.tb_high, t.tb_low);
  752. }
  753. # elif defined(OSSL_POSIX_TIMER_OKAY)
  754. {
  755. struct timespec ts;
  756. # ifdef CLOCK_BOOTTIME
  757. # define CLOCK_TYPE CLOCK_BOOTTIME
  758. # elif defined(_POSIX_MONOTONIC_CLOCK)
  759. # define CLOCK_TYPE CLOCK_MONOTONIC
  760. # else
  761. # define CLOCK_TYPE CLOCK_REALTIME
  762. # endif
  763. if (clock_gettime(CLOCK_TYPE, &ts) == 0)
  764. return TWO32TO64(ts.tv_sec, ts.tv_nsec);
  765. }
  766. # endif
  767. # if defined(__unix__) \
  768. || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
  769. {
  770. struct timeval tv;
  771. if (gettimeofday(&tv, NULL) == 0)
  772. return TWO32TO64(tv.tv_sec, tv.tv_usec);
  773. }
  774. # endif
  775. return time(NULL);
  776. }
  777. #endif /* (defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_SYS_VXWORKS))
  778. || defined(__DJGPP__) */