rand_unix.c 26 KB

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