getrandom.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. /*
  3. * Copyright (C) 2022-2024 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
  4. */
  5. #ifndef _VDSO_GETRANDOM_H
  6. #define _VDSO_GETRANDOM_H
  7. #include <linux/types.h>
  8. #define CHACHA_KEY_SIZE 32
  9. #define CHACHA_BLOCK_SIZE 64
  10. /**
  11. * struct vgetrandom_state - State used by vDSO getrandom().
  12. *
  13. * @batch: One and a half ChaCha20 blocks of buffered RNG output.
  14. *
  15. * @key: Key to be used for generating next batch.
  16. *
  17. * @batch_key: Union of the prior two members, which is exactly two full
  18. * ChaCha20 blocks in size, so that @batch and @key can be filled
  19. * together.
  20. *
  21. * @generation: Snapshot of @rng_info->generation in the vDSO data page at
  22. * the time @key was generated.
  23. *
  24. * @pos: Offset into @batch of the next available random byte.
  25. *
  26. * @in_use: Reentrancy guard for reusing a state within the same thread
  27. * due to signal handlers.
  28. */
  29. struct vgetrandom_state {
  30. union {
  31. struct {
  32. u8 batch[CHACHA_BLOCK_SIZE * 3 / 2];
  33. u32 key[CHACHA_KEY_SIZE / sizeof(u32)];
  34. };
  35. u8 batch_key[CHACHA_BLOCK_SIZE * 2];
  36. };
  37. u64 generation;
  38. u8 pos;
  39. bool in_use;
  40. };
  41. /**
  42. * __arch_chacha20_blocks_nostack - Generate ChaCha20 stream without using the stack.
  43. * @dst_bytes: Destination buffer to hold @nblocks * 64 bytes of output.
  44. * @key: 32-byte input key.
  45. * @counter: 8-byte counter, read on input and updated on return.
  46. * @nblocks: Number of blocks to generate.
  47. *
  48. * Generates a given positive number of blocks of ChaCha20 output with nonce=0, and does not write
  49. * to any stack or memory outside of the parameters passed to it, in order to mitigate stack data
  50. * leaking into forked child processes.
  51. */
  52. extern void __arch_chacha20_blocks_nostack(u8 *dst_bytes, const u32 *key, u32 *counter, size_t nblocks);
  53. /**
  54. * __vdso_getrandom - Architecture-specific vDSO implementation of getrandom() syscall.
  55. * @buffer: Passed to __cvdso_getrandom().
  56. * @len: Passed to __cvdso_getrandom().
  57. * @flags: Passed to __cvdso_getrandom().
  58. * @opaque_state: Passed to __cvdso_getrandom().
  59. * @opaque_len: Passed to __cvdso_getrandom();
  60. *
  61. * This function is implemented by making a single call to to __cvdso_getrandom(), whose
  62. * documentation may be consulted for more information.
  63. *
  64. * Returns: The return value of __cvdso_getrandom().
  65. */
  66. extern ssize_t __vdso_getrandom(void *buffer, size_t len, unsigned int flags, void *opaque_state, size_t opaque_len);
  67. #endif /* _VDSO_GETRANDOM_H */