xref: /dragonfly/sys/sys/csprng.h (revision 78478697)
1 #ifndef _SYS_CSPRNG_H_
2 #define _SYS_CSPRNG_H_
3 
4 #include <crypto/sha2/sha2.h>
5 #include <crypto/chacha/chacha.h>
6 
7 #include <sys/callout.h>
8 #include <sys/spinlock.h>
9 #include <sys/time.h>
10 
11 /* Flags for various calls */
12 #define CSPRNG_TRYLOCK		0x0001
13 #define CSPRNG_UNLIMITED	0x0002
14 
15 struct csprng_pool {
16 	uint64_t	bytes;
17 	SHA256_CTX	hash_ctx;
18 
19 	struct spinlock	lock;
20 };
21 
22 CTASSERT(SHA256_DIGEST_LENGTH == 32);
23 
24 struct csprng_state {
25 	uint8_t		key[SHA256_DIGEST_LENGTH];
26 	uint64_t	nonce;		/* Effectively high 64-bits of ctr */
27 	uint64_t	ctr;
28 
29 	uint64_t	reseed_cnt;	/* Times we have reseeded */
30 
31 	chacha_ctx	cipher_ctx;	/* (Stream) cipher context */
32 
33 	/* Pools and the per-source round robin pool index */
34 	struct csprng_pool pool[32];
35 	uint8_t		src_pool_idx[256];
36 
37 	struct spinlock	lock;
38 	struct callout	reseed_callout;
39 	uint32_t	failed_reseeds;
40 	int		callout_based_reseed;
41 	struct timeval  last_reseed;
42 };
43 
44 int csprng_init(struct csprng_state *state);
45 int csprng_init_reseed(struct csprng_state *state);
46 int csprng_get_random(struct csprng_state *state, uint8_t *out, int bytes,
47     int flags);
48 int csprng_add_entropy(struct csprng_state *state, int src_id,
49     const uint8_t *entropy, size_t bytes, int flags);
50 
51 #endif
52