getrandom.c 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2022-2024 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
  4. */
  5. #include <linux/array_size.h>
  6. #include <linux/minmax.h>
  7. #include <vdso/datapage.h>
  8. #include <vdso/getrandom.h>
  9. #include <vdso/unaligned.h>
  10. #include <asm/vdso/getrandom.h>
  11. #include <uapi/linux/mman.h>
  12. #include <uapi/linux/random.h>
  13. /* Bring in default accessors */
  14. #include <vdso/vsyscall.h>
  15. #undef PAGE_SIZE
  16. #undef PAGE_MASK
  17. #define PAGE_SIZE (1UL << CONFIG_PAGE_SHIFT)
  18. #define PAGE_MASK (~(PAGE_SIZE - 1))
  19. #define MEMCPY_AND_ZERO_SRC(type, dst, src, len) do { \
  20. while (len >= sizeof(type)) { \
  21. __put_unaligned_t(type, __get_unaligned_t(type, src), dst); \
  22. __put_unaligned_t(type, 0, src); \
  23. dst += sizeof(type); \
  24. src += sizeof(type); \
  25. len -= sizeof(type); \
  26. } \
  27. } while (0)
  28. static void memcpy_and_zero_src(void *dst, void *src, size_t len)
  29. {
  30. if (IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) {
  31. if (IS_ENABLED(CONFIG_64BIT))
  32. MEMCPY_AND_ZERO_SRC(u64, dst, src, len);
  33. MEMCPY_AND_ZERO_SRC(u32, dst, src, len);
  34. MEMCPY_AND_ZERO_SRC(u16, dst, src, len);
  35. }
  36. MEMCPY_AND_ZERO_SRC(u8, dst, src, len);
  37. }
  38. /**
  39. * __cvdso_getrandom_data - Generic vDSO implementation of getrandom() syscall.
  40. * @rng_info: Describes state of kernel RNG, memory shared with kernel.
  41. * @buffer: Destination buffer to fill with random bytes.
  42. * @len: Size of @buffer in bytes.
  43. * @flags: Zero or more GRND_* flags.
  44. * @opaque_state: Pointer to an opaque state area.
  45. * @opaque_len: Length of opaque state area.
  46. *
  47. * This implements a "fast key erasure" RNG using ChaCha20, in the same way that the kernel's
  48. * getrandom() syscall does. It periodically reseeds its key from the kernel's RNG, at the same
  49. * schedule that the kernel's RNG is reseeded. If the kernel's RNG is not ready, then this always
  50. * calls into the syscall.
  51. *
  52. * If @buffer, @len, and @flags are 0, and @opaque_len is ~0UL, then @opaque_state is populated
  53. * with a struct vgetrandom_opaque_params and the function returns 0; if it does not return 0,
  54. * this function should not be used.
  55. *
  56. * @opaque_state *must* be allocated by calling mmap(2) using the mmap_prot and mmap_flags fields
  57. * from the struct vgetrandom_opaque_params, and states must not straddle pages. Unless external
  58. * locking is used, one state must be allocated per thread, as it is not safe to call this function
  59. * concurrently with the same @opaque_state. However, it is safe to call this using the same
  60. * @opaque_state that is shared between main code and signal handling code, within the same thread.
  61. *
  62. * Returns: The number of random bytes written to @buffer, or a negative value indicating an error.
  63. */
  64. static __always_inline ssize_t
  65. __cvdso_getrandom_data(const struct vdso_rng_data *rng_info, void *buffer, size_t len,
  66. unsigned int flags, void *opaque_state, size_t opaque_len)
  67. {
  68. ssize_t ret = min_t(size_t, INT_MAX & PAGE_MASK /* = MAX_RW_COUNT */, len);
  69. struct vgetrandom_state *state = opaque_state;
  70. size_t batch_len, nblocks, orig_len = len;
  71. bool in_use, have_retried = false;
  72. void *orig_buffer = buffer;
  73. u64 current_generation;
  74. u32 counter[2] = { 0 };
  75. if (unlikely(opaque_len == ~0UL && !buffer && !len && !flags)) {
  76. struct vgetrandom_opaque_params *params = opaque_state;
  77. params->size_of_opaque_state = sizeof(*state);
  78. params->mmap_prot = PROT_READ | PROT_WRITE;
  79. params->mmap_flags = MAP_DROPPABLE | MAP_ANONYMOUS;
  80. for (size_t i = 0; i < ARRAY_SIZE(params->reserved); ++i)
  81. params->reserved[i] = 0;
  82. return 0;
  83. }
  84. /* The state must not straddle a page, since pages can be zeroed at any time. */
  85. if (unlikely(((unsigned long)opaque_state & ~PAGE_MASK) + sizeof(*state) > PAGE_SIZE))
  86. return -EFAULT;
  87. /* Handle unexpected flags by falling back to the kernel. */
  88. if (unlikely(flags & ~(GRND_NONBLOCK | GRND_RANDOM | GRND_INSECURE)))
  89. goto fallback_syscall;
  90. /* If the caller passes the wrong size, which might happen due to CRIU, fallback. */
  91. if (unlikely(opaque_len != sizeof(*state)))
  92. goto fallback_syscall;
  93. /*
  94. * If the kernel's RNG is not yet ready, then it's not possible to provide random bytes from
  95. * userspace, because A) the various @flags require this to block, or not, depending on
  96. * various factors unavailable to userspace, and B) the kernel's behavior before the RNG is
  97. * ready is to reseed from the entropy pool at every invocation.
  98. */
  99. if (unlikely(!READ_ONCE(rng_info->is_ready)))
  100. goto fallback_syscall;
  101. /*
  102. * This condition is checked after @rng_info->is_ready, because before the kernel's RNG is
  103. * initialized, the @flags parameter may require this to block or return an error, even when
  104. * len is zero.
  105. */
  106. if (unlikely(!len))
  107. return 0;
  108. /*
  109. * @state->in_use is basic reentrancy protection against this running in a signal handler
  110. * with the same @opaque_state, but obviously not atomic wrt multiple CPUs or more than one
  111. * level of reentrancy. If a signal interrupts this after reading @state->in_use, but before
  112. * writing @state->in_use, there is still no race, because the signal handler will run to
  113. * its completion before returning execution.
  114. */
  115. in_use = READ_ONCE(state->in_use);
  116. if (unlikely(in_use))
  117. /* The syscall simply fills the buffer and does not touch @state, so fallback. */
  118. goto fallback_syscall;
  119. WRITE_ONCE(state->in_use, true);
  120. retry_generation:
  121. /*
  122. * @rng_info->generation must always be read here, as it serializes @state->key with the
  123. * kernel's RNG reseeding schedule.
  124. */
  125. current_generation = READ_ONCE(rng_info->generation);
  126. /*
  127. * If @state->generation doesn't match the kernel RNG's generation, then it means the
  128. * kernel's RNG has reseeded, and so @state->key is reseeded as well.
  129. */
  130. if (unlikely(state->generation != current_generation)) {
  131. /*
  132. * Write the generation before filling the key, in case of fork. If there is a fork
  133. * just after this line, the parent and child will get different random bytes from
  134. * the syscall, which is good. However, were this line to occur after the getrandom
  135. * syscall, then both child and parent could have the same bytes and the same
  136. * generation counter, so the fork would not be detected. Therefore, write
  137. * @state->generation before the call to the getrandom syscall.
  138. */
  139. WRITE_ONCE(state->generation, current_generation);
  140. /*
  141. * Prevent the syscall from being reordered wrt current_generation. Pairs with the
  142. * smp_store_release(&vdso_k_rng_data->generation) in random.c.
  143. */
  144. smp_rmb();
  145. /* Reseed @state->key using fresh bytes from the kernel. */
  146. if (getrandom_syscall(state->key, sizeof(state->key), 0) != sizeof(state->key)) {
  147. /*
  148. * If the syscall failed to refresh the key, then @state->key is now
  149. * invalid, so invalidate the generation so that it is not used again, and
  150. * fallback to using the syscall entirely.
  151. */
  152. WRITE_ONCE(state->generation, 0);
  153. /*
  154. * Set @state->in_use to false only after the last write to @state in the
  155. * line above.
  156. */
  157. WRITE_ONCE(state->in_use, false);
  158. goto fallback_syscall;
  159. }
  160. /*
  161. * Set @state->pos to beyond the end of the batch, so that the batch is refilled
  162. * using the new key.
  163. */
  164. state->pos = sizeof(state->batch);
  165. }
  166. /* Set len to the total amount of bytes that this function is allowed to read, ret. */
  167. len = ret;
  168. more_batch:
  169. /*
  170. * First use bytes out of @state->batch, which may have been filled by the last call to this
  171. * function.
  172. */
  173. batch_len = min_t(size_t, sizeof(state->batch) - state->pos, len);
  174. if (batch_len) {
  175. /* Zeroing at the same time as memcpying helps preserve forward secrecy. */
  176. memcpy_and_zero_src(buffer, state->batch + state->pos, batch_len);
  177. state->pos += batch_len;
  178. buffer += batch_len;
  179. len -= batch_len;
  180. }
  181. if (!len) {
  182. /* Prevent the loop from being reordered wrt ->generation. */
  183. barrier();
  184. /*
  185. * Since @rng_info->generation will never be 0, re-read @state->generation, rather
  186. * than using the local current_generation variable, to learn whether a fork
  187. * occurred or if @state was zeroed due to memory pressure. Primarily, though, this
  188. * indicates whether the kernel's RNG has reseeded, in which case generate a new key
  189. * and start over.
  190. */
  191. if (unlikely(READ_ONCE(state->generation) != READ_ONCE(rng_info->generation))) {
  192. /*
  193. * Prevent this from looping forever in case of low memory or racing with a
  194. * user force-reseeding the kernel's RNG using the ioctl.
  195. */
  196. if (have_retried) {
  197. WRITE_ONCE(state->in_use, false);
  198. goto fallback_syscall;
  199. }
  200. have_retried = true;
  201. buffer = orig_buffer;
  202. goto retry_generation;
  203. }
  204. /*
  205. * Set @state->in_use to false only when there will be no more reads or writes of
  206. * @state.
  207. */
  208. WRITE_ONCE(state->in_use, false);
  209. return ret;
  210. }
  211. /* Generate blocks of RNG output directly into @buffer while there's enough room left. */
  212. nblocks = len / CHACHA_BLOCK_SIZE;
  213. if (nblocks) {
  214. __arch_chacha20_blocks_nostack(buffer, state->key, counter, nblocks);
  215. buffer += nblocks * CHACHA_BLOCK_SIZE;
  216. len -= nblocks * CHACHA_BLOCK_SIZE;
  217. }
  218. BUILD_BUG_ON(sizeof(state->batch_key) % CHACHA_BLOCK_SIZE != 0);
  219. /* Refill the batch and overwrite the key, in order to preserve forward secrecy. */
  220. __arch_chacha20_blocks_nostack(state->batch_key, state->key, counter,
  221. sizeof(state->batch_key) / CHACHA_BLOCK_SIZE);
  222. /* Since the batch was just refilled, set the position back to 0 to indicate a full batch. */
  223. state->pos = 0;
  224. goto more_batch;
  225. fallback_syscall:
  226. return getrandom_syscall(orig_buffer, orig_len, flags);
  227. }
  228. static __always_inline ssize_t
  229. __cvdso_getrandom(void *buffer, size_t len, unsigned int flags, void *opaque_state, size_t opaque_len)
  230. {
  231. return __cvdso_getrandom_data(__arch_get_vdso_u_rng_data(), buffer, len, flags,
  232. opaque_state, opaque_len);
  233. }