rand_unix.c 26 KB

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