randombytes_sysrandom.c 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. #include <assert.h>
  2. #include <errno.h>
  3. #include <fcntl.h>
  4. #include <limits.h>
  5. #include <stdint.h>
  6. #include <string.h>
  7. #ifndef _WIN32
  8. # include <unistd.h>
  9. #endif
  10. #include <stdlib.h>
  11. #include <sys/types.h>
  12. #ifndef _WIN32
  13. # include <sys/stat.h>
  14. # include <sys/time.h>
  15. #endif
  16. #ifdef __linux__
  17. # define _LINUX_SOURCE
  18. #endif
  19. #ifdef HAVE_SYS_RANDOM_H
  20. # include <sys/random.h>
  21. #endif
  22. #ifdef __linux__
  23. # ifdef HAVE_GETRANDOM
  24. # define HAVE_LINUX_COMPATIBLE_GETRANDOM
  25. # else
  26. # include <sys/syscall.h>
  27. # if defined(SYS_getrandom) && defined(__NR_getrandom)
  28. # define getrandom(B, S, F) syscall(SYS_getrandom, (B), (int) (S), (F))
  29. # define HAVE_LINUX_COMPATIBLE_GETRANDOM
  30. # endif
  31. # endif
  32. #elif defined(__FreeBSD__)
  33. # include <sys/param.h>
  34. # if defined(__FreeBSD_version) && __FreeBSD_version >= 1200000
  35. # define HAVE_LINUX_COMPATIBLE_GETRANDOM
  36. # endif
  37. #endif
  38. #if !defined(NO_BLOCKING_RANDOM_POLL) && defined(__linux__)
  39. # define BLOCK_ON_DEV_RANDOM
  40. #endif
  41. #ifdef BLOCK_ON_DEV_RANDOM
  42. # include <poll.h>
  43. #endif
  44. #include "core.h"
  45. #include "private/common.h"
  46. #include "randombytes.h"
  47. #include "randombytes_sysrandom.h"
  48. #include "utils.h"
  49. #ifdef _WIN32
  50. /* `RtlGenRandom` is used over `CryptGenRandom` on Microsoft Windows based systems:
  51. * - `CryptGenRandom` requires pulling in `CryptoAPI` which causes unnecessary
  52. * memory overhead if this API is not being used for other purposes
  53. * - `RtlGenRandom` is thus called directly instead. A detailed explanation
  54. * can be found here: https://blogs.msdn.microsoft.com/michael_howard/2005/01/14/cryptographically-secure-random-number-on-windows-without-using-cryptoapi/
  55. *
  56. * In spite of the disclaimer on the `RtlGenRandom` documentation page that was
  57. * written back in the Windows XP days, this function is here to stay. The CRT
  58. * function `rand_s()` directly depends on it, so touching it would break many
  59. * applications released since Windows XP.
  60. *
  61. * Also note that Rust, Firefox and BoringSSL (thus, Google Chrome and everything
  62. * based on Chromium) also depend on it, and that libsodium allows the RNG to be
  63. * replaced without patching nor recompiling the library.
  64. */
  65. # include <windows.h>
  66. # define RtlGenRandom SystemFunction036
  67. # if defined(__cplusplus)
  68. extern "C"
  69. # endif
  70. BOOLEAN NTAPI RtlGenRandom(PVOID RandomBuffer, ULONG RandomBufferLength);
  71. # pragma comment(lib, "advapi32.lib")
  72. #endif
  73. #if defined(__OpenBSD__) || defined(__CloudABI__) || defined(__wasi__)
  74. # define HAVE_SAFE_ARC4RANDOM 1
  75. #endif
  76. #ifndef SSIZE_MAX
  77. # define SSIZE_MAX (SIZE_MAX / 2 - 1)
  78. #endif
  79. #ifdef HAVE_SAFE_ARC4RANDOM
  80. static uint32_t
  81. randombytes_sysrandom(void)
  82. {
  83. return arc4random();
  84. }
  85. static void
  86. randombytes_sysrandom_stir(void)
  87. {
  88. }
  89. static void
  90. randombytes_sysrandom_buf(void * const buf, const size_t size)
  91. {
  92. arc4random_buf(buf, size);
  93. }
  94. static int
  95. randombytes_sysrandom_close(void)
  96. {
  97. return 0;
  98. }
  99. #else /* HAVE_SAFE_ARC4RANDOM */
  100. typedef struct SysRandom_ {
  101. int random_data_source_fd;
  102. int initialized;
  103. int getrandom_available;
  104. } SysRandom;
  105. static SysRandom stream = {
  106. SODIUM_C99(.random_data_source_fd =) -1,
  107. SODIUM_C99(.initialized =) 0,
  108. SODIUM_C99(.getrandom_available =) 0
  109. };
  110. # ifndef _WIN32
  111. static ssize_t
  112. safe_read(const int fd, void * const buf_, size_t size)
  113. {
  114. unsigned char *buf = (unsigned char *) buf_;
  115. ssize_t readnb;
  116. assert(size > (size_t) 0U);
  117. assert(size <= SSIZE_MAX);
  118. do {
  119. while ((readnb = read(fd, buf, size)) < (ssize_t) 0 &&
  120. (errno == EINTR || errno == EAGAIN)); /* LCOV_EXCL_LINE */
  121. if (readnb < (ssize_t) 0) {
  122. return readnb; /* LCOV_EXCL_LINE */
  123. }
  124. if (readnb == (ssize_t) 0) {
  125. break; /* LCOV_EXCL_LINE */
  126. }
  127. size -= (size_t) readnb;
  128. buf += readnb;
  129. } while (size > (ssize_t) 0);
  130. return (ssize_t) (buf - (unsigned char *) buf_);
  131. }
  132. # ifdef BLOCK_ON_DEV_RANDOM
  133. static int
  134. randombytes_block_on_dev_random(void)
  135. {
  136. struct pollfd pfd;
  137. int fd;
  138. int pret;
  139. fd = open("/dev/random", O_RDONLY);
  140. if (fd == -1) {
  141. return 0;
  142. }
  143. pfd.fd = fd;
  144. pfd.events = POLLIN;
  145. pfd.revents = 0;
  146. do {
  147. pret = poll(&pfd, 1, -1);
  148. } while (pret < 0 && (errno == EINTR || errno == EAGAIN));
  149. if (pret != 1) {
  150. (void) close(fd);
  151. errno = EIO;
  152. return -1;
  153. }
  154. return close(fd);
  155. }
  156. # endif /* BLOCK_ON_DEV_RANDOM */
  157. static int
  158. randombytes_sysrandom_random_dev_open(void)
  159. {
  160. /* LCOV_EXCL_START */
  161. struct stat st;
  162. static const char *devices[] = {
  163. # ifndef USE_BLOCKING_RANDOM
  164. "/dev/urandom",
  165. # endif
  166. "/dev/random", NULL
  167. };
  168. const char **device = devices;
  169. int fd;
  170. # ifdef BLOCK_ON_DEV_RANDOM
  171. if (randombytes_block_on_dev_random() != 0) {
  172. return -1;
  173. }
  174. # endif
  175. do {
  176. fd = open(*device, O_RDONLY);
  177. if (fd != -1) {
  178. if (fstat(fd, &st) == 0 &&
  179. # ifdef __COMPCERT__
  180. 1
  181. # elif defined(S_ISNAM)
  182. (S_ISNAM(st.st_mode) || S_ISCHR(st.st_mode))
  183. # else
  184. S_ISCHR(st.st_mode)
  185. # endif
  186. ) {
  187. # if defined(F_SETFD) && defined(FD_CLOEXEC)
  188. (void) fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
  189. # endif
  190. return fd;
  191. }
  192. (void) close(fd);
  193. } else if (errno == EINTR) {
  194. continue;
  195. }
  196. device++;
  197. } while (*device != NULL);
  198. errno = EIO;
  199. return -1;
  200. /* LCOV_EXCL_STOP */
  201. }
  202. # ifdef HAVE_LINUX_COMPATIBLE_GETRANDOM
  203. static int
  204. _randombytes_linux_getrandom(void * const buf, const size_t size)
  205. {
  206. int readnb;
  207. assert(size <= 256U);
  208. do {
  209. readnb = getrandom(buf, size, 0);
  210. } while (readnb < 0 && (errno == EINTR || errno == EAGAIN));
  211. return (readnb == (int) size) - 1;
  212. }
  213. static int
  214. randombytes_linux_getrandom(void * const buf_, size_t size)
  215. {
  216. unsigned char *buf = (unsigned char *) buf_;
  217. size_t chunk_size = 256U;
  218. do {
  219. if (size < chunk_size) {
  220. chunk_size = size;
  221. assert(chunk_size > (size_t) 0U);
  222. }
  223. if (_randombytes_linux_getrandom(buf, chunk_size) != 0) {
  224. return -1;
  225. }
  226. size -= chunk_size;
  227. buf += chunk_size;
  228. } while (size > (size_t) 0U);
  229. return 0;
  230. }
  231. # endif /* HAVE_LINUX_COMPATIBLE_GETRANDOM */
  232. static void
  233. randombytes_sysrandom_init(void)
  234. {
  235. const int errno_save = errno;
  236. # ifdef HAVE_LINUX_COMPATIBLE_GETRANDOM
  237. {
  238. unsigned char fodder[16];
  239. if (randombytes_linux_getrandom(fodder, sizeof fodder) == 0) {
  240. stream.getrandom_available = 1;
  241. errno = errno_save;
  242. return;
  243. }
  244. stream.getrandom_available = 0;
  245. }
  246. # endif
  247. if ((stream.random_data_source_fd =
  248. randombytes_sysrandom_random_dev_open()) == -1) {
  249. sodium_misuse(); /* LCOV_EXCL_LINE */
  250. }
  251. errno = errno_save;
  252. }
  253. # else /* _WIN32 */
  254. static void
  255. randombytes_sysrandom_init(void)
  256. {
  257. }
  258. # endif /* _WIN32 */
  259. static void
  260. randombytes_sysrandom_stir(void)
  261. {
  262. if (stream.initialized == 0) {
  263. randombytes_sysrandom_init();
  264. stream.initialized = 1;
  265. }
  266. }
  267. static void
  268. randombytes_sysrandom_stir_if_needed(void)
  269. {
  270. if (stream.initialized == 0) {
  271. randombytes_sysrandom_stir();
  272. }
  273. }
  274. static int
  275. randombytes_sysrandom_close(void)
  276. {
  277. int ret = -1;
  278. # ifndef _WIN32
  279. if (stream.random_data_source_fd != -1 &&
  280. close(stream.random_data_source_fd) == 0) {
  281. stream.random_data_source_fd = -1;
  282. stream.initialized = 0;
  283. ret = 0;
  284. }
  285. # ifdef HAVE_LINUX_COMPATIBLE_GETRANDOM
  286. if (stream.getrandom_available != 0) {
  287. ret = 0;
  288. }
  289. # endif
  290. # else /* _WIN32 */
  291. if (stream.initialized != 0) {
  292. stream.initialized = 0;
  293. ret = 0;
  294. }
  295. # endif /* _WIN32 */
  296. return ret;
  297. }
  298. static void
  299. randombytes_sysrandom_buf(void * const buf, const size_t size)
  300. {
  301. randombytes_sysrandom_stir_if_needed();
  302. # if defined(ULLONG_MAX) && defined(SIZE_MAX)
  303. # if SIZE_MAX > ULLONG_MAX
  304. /* coverity[result_independent_of_operands] */
  305. assert(size <= ULLONG_MAX);
  306. # endif
  307. # endif
  308. # ifndef _WIN32
  309. # ifdef HAVE_LINUX_COMPATIBLE_GETRANDOM
  310. if (stream.getrandom_available != 0) {
  311. if (randombytes_linux_getrandom(buf, size) != 0) {
  312. sodium_misuse(); /* LCOV_EXCL_LINE */
  313. }
  314. return;
  315. }
  316. # endif
  317. if (stream.random_data_source_fd == -1 ||
  318. safe_read(stream.random_data_source_fd, buf, size) != (ssize_t) size) {
  319. sodium_misuse(); /* LCOV_EXCL_LINE */
  320. }
  321. # else /* _WIN32 */
  322. COMPILER_ASSERT(randombytes_BYTES_MAX <= 0xffffffffUL);
  323. if (size > (size_t) 0xffffffffUL) {
  324. sodium_misuse(); /* LCOV_EXCL_LINE */
  325. }
  326. if (! RtlGenRandom((PVOID) buf, (ULONG) size)) {
  327. sodium_misuse(); /* LCOV_EXCL_LINE */
  328. }
  329. # endif /* _WIN32 */
  330. }
  331. static uint32_t
  332. randombytes_sysrandom(void)
  333. {
  334. uint32_t r;
  335. randombytes_sysrandom_buf(&r, sizeof r);
  336. return r;
  337. }
  338. #endif /* HAVE_SAFE_ARC4RANDOM */
  339. static const char *
  340. randombytes_sysrandom_implementation_name(void)
  341. {
  342. return "sysrandom";
  343. }
  344. struct randombytes_implementation randombytes_sysrandom_implementation = {
  345. SODIUM_C99(.implementation_name =) randombytes_sysrandom_implementation_name,
  346. SODIUM_C99(.random =) randombytes_sysrandom,
  347. SODIUM_C99(.stir =) randombytes_sysrandom_stir,
  348. SODIUM_C99(.uniform =) NULL,
  349. SODIUM_C99(.buf =) randombytes_sysrandom_buf,
  350. SODIUM_C99(.close =) randombytes_sysrandom_close
  351. };