rand_unix.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. /*
  2. * Copyright 1995-2018 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. #define _GNU_SOURCE
  10. #include "e_os.h"
  11. #include <stdio.h>
  12. #include "internal/cryptlib.h"
  13. #include <openssl/rand.h>
  14. #include "rand_lcl.h"
  15. #include "internal/rand_int.h"
  16. #include <stdio.h>
  17. #if defined(__linux)
  18. # include <sys/syscall.h>
  19. #endif
  20. #if defined(__FreeBSD__)
  21. # include <sys/types.h>
  22. # include <sys/sysctl.h>
  23. # include <sys/param.h>
  24. #endif
  25. #if defined(__OpenBSD__)
  26. # include <sys/param.h>
  27. #endif
  28. #ifdef OPENSSL_SYS_UNIX
  29. # include <sys/types.h>
  30. # include <unistd.h>
  31. # include <sys/time.h>
  32. static uint64_t get_time_stamp(void);
  33. static uint64_t get_timer_bits(void);
  34. /* Macro to convert two thirty two bit values into a sixty four bit one */
  35. # define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
  36. /*
  37. * Check for the existence and support of POSIX timers. The standard
  38. * says that the _POSIX_TIMERS macro will have a positive value if they
  39. * are available.
  40. *
  41. * However, we want an additional constraint: that the timer support does
  42. * not require an extra library dependency. Early versions of glibc
  43. * require -lrt to be specified on the link line to access the timers,
  44. * so this needs to be checked for.
  45. *
  46. * It is worse because some libraries define __GLIBC__ but don't
  47. * support the version testing macro (e.g. uClibc). This means
  48. * an extra check is needed.
  49. *
  50. * The final condition is:
  51. * "have posix timers and either not glibc or glibc without -lrt"
  52. *
  53. * The nested #if sequences are required to avoid using a parameterised
  54. * macro that might be undefined.
  55. */
  56. # undef OSSL_POSIX_TIMER_OKAY
  57. # if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
  58. # if defined(__GLIBC__)
  59. # if defined(__GLIBC_PREREQ)
  60. # if __GLIBC_PREREQ(2, 17)
  61. # define OSSL_POSIX_TIMER_OKAY
  62. # endif
  63. # endif
  64. # else
  65. # define OSSL_POSIX_TIMER_OKAY
  66. # endif
  67. # endif
  68. #endif
  69. int syscall_random(void *buf, size_t buflen);
  70. #if (defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)) && \
  71. !defined(OPENSSL_RAND_SEED_NONE)
  72. # error "UEFI and VXWorks only support seeding NONE"
  73. #endif
  74. #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
  75. || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
  76. || defined(OPENSSL_SYS_UEFI))
  77. # if defined(OPENSSL_SYS_VOS)
  78. # ifndef OPENSSL_RAND_SEED_OS
  79. # error "Unsupported seeding method configured; must be os"
  80. # endif
  81. # if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
  82. # error "Unsupported HP-PA and IA32 at the same time."
  83. # endif
  84. # if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
  85. # error "Must have one of HP-PA or IA32"
  86. # endif
  87. /*
  88. * The following algorithm repeatedly samples the real-time clock (RTC) to
  89. * generate a sequence of unpredictable data. The algorithm relies upon the
  90. * uneven execution speed of the code (due to factors such as cache misses,
  91. * interrupts, bus activity, and scheduling) and upon the rather large
  92. * relative difference between the speed of the clock and the rate at which
  93. * it can be read. If it is ported to an environment where execution speed
  94. * is more constant or where the RTC ticks at a much slower rate, or the
  95. * clock can be read with fewer instructions, it is likely that the results
  96. * would be far more predictable. This should only be used for legacy
  97. * platforms.
  98. *
  99. * As a precaution, we assume only 2 bits of entropy per byte.
  100. */
  101. size_t rand_pool_acquire_entropy(RAND_POOL *pool)
  102. {
  103. short int code;
  104. int i, k;
  105. size_t bytes_needed;
  106. struct timespec ts;
  107. unsigned char v;
  108. # ifdef OPENSSL_SYS_VOS_HPPA
  109. long duration;
  110. extern void s$sleep(long *_duration, short int *_code);
  111. # else
  112. long long duration;
  113. extern void s$sleep2(long long *_duration, short int *_code);
  114. # endif
  115. bytes_needed = rand_pool_bytes_needed(pool, 2 /*entropy_per_byte*/);
  116. for (i = 0; i < bytes_needed; i++) {
  117. /*
  118. * burn some cpu; hope for interrupts, cache collisions, bus
  119. * interference, etc.
  120. */
  121. for (k = 0; k < 99; k++)
  122. ts.tv_nsec = random();
  123. # ifdef OPENSSL_SYS_VOS_HPPA
  124. /* sleep for 1/1024 of a second (976 us). */
  125. duration = 1;
  126. s$sleep(&duration, &code);
  127. # else
  128. /* sleep for 1/65536 of a second (15 us). */
  129. duration = 1;
  130. s$sleep2(&duration, &code);
  131. # endif
  132. /* Get wall clock time, take 8 bits. */
  133. clock_gettime(CLOCK_REALTIME, &ts);
  134. v = (unsigned char)(ts.tv_nsec & 0xFF);
  135. rand_pool_add(pool, arg, &v, sizeof(v) , 2);
  136. }
  137. return rand_pool_entropy_available(pool);
  138. }
  139. # else
  140. # if defined(OPENSSL_RAND_SEED_EGD) && \
  141. (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
  142. # error "Seeding uses EGD but EGD is turned off or no device given"
  143. # endif
  144. # if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
  145. # error "Seeding uses urandom but DEVRANDOM is not configured"
  146. # endif
  147. # if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
  148. # if __GLIBC_PREREQ(2, 25)
  149. # define OPENSSL_HAVE_GETRANDOM
  150. # endif
  151. # endif
  152. # if (defined(__FreeBSD__) && __FreeBSD_version >= 1200061)
  153. # define OPENSSL_HAVE_GETRANDOM
  154. # endif
  155. # if defined(OPENSSL_HAVE_GETRANDOM)
  156. # include <sys/random.h>
  157. # endif
  158. # if defined(OPENSSL_RAND_SEED_OS)
  159. # if !defined(DEVRANDOM)
  160. # error "OS seeding requires DEVRANDOM to be configured"
  161. # endif
  162. # define OPENSSL_RAND_SEED_GETRANDOM
  163. # define OPENSSL_RAND_SEED_DEVRANDOM
  164. # endif
  165. # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
  166. # error "librandom not (yet) supported"
  167. # endif
  168. # if defined(__FreeBSD__) && defined(KERN_ARND)
  169. /*
  170. * sysctl_random(): Use sysctl() to read a random number from the kernel
  171. * Returns the size on success, 0 on failure.
  172. */
  173. static size_t sysctl_random(char *buf, size_t buflen)
  174. {
  175. int mib[2];
  176. size_t done = 0;
  177. size_t len;
  178. /*
  179. * Old implementations returned longs, newer versions support variable
  180. * sizes up to 256 byte. The code below would not work properly when
  181. * the sysctl returns long and we want to request something not a multiple
  182. * of longs, which should never be the case.
  183. */
  184. if (!ossl_assert(buflen % sizeof(long) == 0))
  185. return 0;
  186. mib[0] = CTL_KERN;
  187. mib[1] = KERN_ARND;
  188. do {
  189. len = buflen;
  190. if (sysctl(mib, 2, buf, &len, NULL, 0) == -1)
  191. return done;
  192. done += len;
  193. buf += len;
  194. buflen -= len;
  195. } while (buflen > 0);
  196. return done;
  197. }
  198. # endif
  199. /*
  200. * syscall_random(): Try to get random data using a system call
  201. * returns the number of bytes returned in buf, or <= 0 on error.
  202. */
  203. int syscall_random(void *buf, size_t buflen)
  204. {
  205. # if defined(OPENSSL_HAVE_GETRANDOM)
  206. return (int)getrandom(buf, buflen, 0);
  207. # endif
  208. # if defined(__linux) && defined(SYS_getrandom)
  209. return (int)syscall(SYS_getrandom, buf, buflen, 0);
  210. # endif
  211. # if defined(__FreeBSD__) && defined(KERN_ARND)
  212. return (int)sysctl_random(buf, buflen);
  213. # endif
  214. /* Supported since OpenBSD 5.6 */
  215. # if defined(__OpenBSD__) && OpenBSD >= 201411
  216. return getentropy(buf, buflen);
  217. # endif
  218. return -1;
  219. }
  220. /*
  221. * Try the various seeding methods in turn, exit when successful.
  222. *
  223. * TODO(DRBG): If more than one entropy source is available, is it
  224. * preferable to stop as soon as enough entropy has been collected
  225. * (as favored by @rsalz) or should one rather be defensive and add
  226. * more entropy than requested and/or from different sources?
  227. *
  228. * Currently, the user can select multiple entropy sources in the
  229. * configure step, yet in practice only the first available source
  230. * will be used. A more flexible solution has been requested, but
  231. * currently it is not clear how this can be achieved without
  232. * overengineering the problem. There are many parameters which
  233. * could be taken into account when selecting the order and amount
  234. * of input from the different entropy sources (trust, quality,
  235. * possibility of blocking).
  236. */
  237. size_t rand_pool_acquire_entropy(RAND_POOL *pool)
  238. {
  239. # ifdef OPENSSL_RAND_SEED_NONE
  240. return rand_pool_entropy_available(pool);
  241. # else
  242. size_t bytes_needed;
  243. size_t entropy_available = 0;
  244. unsigned char *buffer;
  245. # ifdef OPENSSL_RAND_SEED_GETRANDOM
  246. bytes_needed = rand_pool_bytes_needed(pool, 8 /*entropy_per_byte*/);
  247. buffer = rand_pool_add_begin(pool, bytes_needed);
  248. if (buffer != NULL) {
  249. size_t bytes = 0;
  250. if (syscall_random(buffer, bytes_needed) == (int)bytes_needed)
  251. bytes = bytes_needed;
  252. rand_pool_add_end(pool, bytes, 8 * bytes);
  253. entropy_available = rand_pool_entropy_available(pool);
  254. }
  255. if (entropy_available > 0)
  256. return entropy_available;
  257. # endif
  258. # if defined(OPENSSL_RAND_SEED_LIBRANDOM)
  259. {
  260. /* Not yet implemented. */
  261. }
  262. # endif
  263. # ifdef OPENSSL_RAND_SEED_DEVRANDOM
  264. bytes_needed = rand_pool_bytes_needed(pool, 8 /*entropy_per_byte*/);
  265. if (bytes_needed > 0) {
  266. static const char *paths[] = { DEVRANDOM, NULL };
  267. FILE *fp;
  268. int i;
  269. for (i = 0; paths[i] != NULL; i++) {
  270. if ((fp = fopen(paths[i], "rb")) == NULL)
  271. continue;
  272. setbuf(fp, NULL);
  273. buffer = rand_pool_add_begin(pool, bytes_needed);
  274. if (buffer != NULL) {
  275. size_t bytes = 0;
  276. if (fread(buffer, 1, bytes_needed, fp) == bytes_needed)
  277. bytes = bytes_needed;
  278. rand_pool_add_end(pool, bytes, 8 * bytes);
  279. entropy_available = rand_pool_entropy_available(pool);
  280. }
  281. fclose(fp);
  282. if (entropy_available > 0)
  283. return entropy_available;
  284. bytes_needed = rand_pool_bytes_needed(pool, 8 /*entropy_per_byte*/);
  285. }
  286. }
  287. # endif
  288. # ifdef OPENSSL_RAND_SEED_RDTSC
  289. entropy_available = rand_acquire_entropy_from_tsc(pool);
  290. if (entropy_available > 0)
  291. return entropy_available;
  292. # endif
  293. # ifdef OPENSSL_RAND_SEED_RDCPU
  294. entropy_available = rand_acquire_entropy_from_cpu(pool);
  295. if (entropy_available > 0)
  296. return entropy_available;
  297. # endif
  298. # ifdef OPENSSL_RAND_SEED_EGD
  299. bytes_needed = rand_pool_bytes_needed(pool, 8 /*entropy_per_byte*/);
  300. if (bytes_needed > 0) {
  301. static const char *paths[] = { DEVRANDOM_EGD, NULL };
  302. int i;
  303. for (i = 0; paths[i] != NULL; i++) {
  304. buffer = rand_pool_add_begin(pool, bytes_needed);
  305. if (buffer != NULL) {
  306. size_t bytes = 0;
  307. int num = RAND_query_egd_bytes(paths[i],
  308. buffer, (int)bytes_needed);
  309. if (num == (int)bytes_needed)
  310. bytes = bytes_needed;
  311. rand_pool_add_end(pool, bytes, 8 * bytes);
  312. entropy_available = rand_pool_entropy_available(pool);
  313. }
  314. if (entropy_available > 0)
  315. return entropy_available;
  316. }
  317. }
  318. # endif
  319. return rand_pool_entropy_available(pool);
  320. # endif
  321. }
  322. # endif
  323. #endif
  324. #ifdef OPENSSL_SYS_UNIX
  325. int rand_pool_add_nonce_data(RAND_POOL *pool)
  326. {
  327. struct {
  328. pid_t pid;
  329. CRYPTO_THREAD_ID tid;
  330. uint64_t time;
  331. } data = { 0 };
  332. /*
  333. * Add process id, thread id, and a high resolution timestamp to
  334. * ensure that the nonce is unique whith high probability for
  335. * different process instances.
  336. */
  337. data.pid = getpid();
  338. data.tid = CRYPTO_THREAD_get_current_id();
  339. data.time = get_time_stamp();
  340. return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
  341. }
  342. int rand_pool_add_additional_data(RAND_POOL *pool)
  343. {
  344. struct {
  345. CRYPTO_THREAD_ID tid;
  346. uint64_t time;
  347. } data = { 0 };
  348. /*
  349. * Add some noise from the thread id and a high resolution timer.
  350. * The thread id adds a little randomness if the drbg is accessed
  351. * concurrently (which is the case for the <master> drbg).
  352. */
  353. data.tid = CRYPTO_THREAD_get_current_id();
  354. data.time = get_timer_bits();
  355. return rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0);
  356. }
  357. /*
  358. * Get the current time with the highest possible resolution
  359. *
  360. * The time stamp is added to the nonce, so it is optimized for not repeating.
  361. * The current time is ideal for this purpose, provided the computer's clock
  362. * is synchronized.
  363. */
  364. static uint64_t get_time_stamp(void)
  365. {
  366. # if defined(OSSL_POSIX_TIMER_OKAY)
  367. {
  368. struct timespec ts;
  369. if (clock_gettime(CLOCK_REALTIME, &ts) == 0)
  370. return TWO32TO64(ts.tv_sec, ts.tv_nsec);
  371. }
  372. # endif
  373. # if defined(__unix__) \
  374. || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
  375. {
  376. struct timeval tv;
  377. if (gettimeofday(&tv, NULL) == 0)
  378. return TWO32TO64(tv.tv_sec, tv.tv_usec);
  379. }
  380. # endif
  381. return time(NULL);
  382. }
  383. /*
  384. * Get an arbitrary timer value of the highest possible resolution
  385. *
  386. * The timer value is added as random noise to the additional data,
  387. * which is not considered a trusted entropy sourec, so any result
  388. * is acceptable.
  389. */
  390. static uint64_t get_timer_bits(void)
  391. {
  392. uint64_t res = OPENSSL_rdtsc();
  393. if (res != 0)
  394. return res;
  395. # if defined(__sun) || defined(__hpux)
  396. return gethrtime();
  397. # elif defined(_AIX)
  398. {
  399. timebasestruct_t t;
  400. read_wall_time(&t, TIMEBASE_SZ);
  401. return TWO32TO64(t.tb_high, t.tb_low);
  402. }
  403. # elif defined(OSSL_POSIX_TIMER_OKAY)
  404. {
  405. struct timespec ts;
  406. # ifdef CLOCK_BOOTTIME
  407. # define CLOCK_TYPE CLOCK_BOOTTIME
  408. # elif defined(_POSIX_MONOTONIC_CLOCK)
  409. # define CLOCK_TYPE CLOCK_MONOTONIC
  410. # else
  411. # define CLOCK_TYPE CLOCK_REALTIME
  412. # endif
  413. if (clock_gettime(CLOCK_TYPE, &ts) == 0)
  414. return TWO32TO64(ts.tv_sec, ts.tv_nsec);
  415. }
  416. # endif
  417. # if defined(__unix__) \
  418. || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
  419. {
  420. struct timeval tv;
  421. if (gettimeofday(&tv, NULL) == 0)
  422. return TWO32TO64(tv.tv_sec, tv.tv_usec);
  423. }
  424. # endif
  425. return time(NULL);
  426. }
  427. #endif