e22d5d44a0b50fd4b2d95c7fe0bfb560c456f3d4
[BearSSL] / inc / bearssl_rand.h
1 /*
2 * Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25 #ifndef BR_BEARSSL_RAND_H__
26 #define BR_BEARSSL_RAND_H__
27
28 #include <stddef.h>
29 #include <stdint.h>
30
31 #include "bearssl_block.h"
32
33 #ifdef __cplusplus
34 extern "C" {
35 #endif
36
37 /** \file bearssl_rand.h
38 *
39 * # Pseudo-Random Generators
40 *
41 * A PRNG is a state-based engine that outputs pseudo-random bytes on
42 * demand. It is initialized with an initial seed, and additional seed
43 * bytes can be added afterwards. Bytes produced depend on the seeds and
44 * also on the exact sequence of calls (including sizes requested for
45 * each call).
46 *
47 *
48 * ## Procedural and OOP API
49 *
50 * For the PRNG of name "`xxx`", two API are provided. The _procedural_
51 * API defined a context structure `br_xxx_context` and three functions:
52 *
53 * - `br_xxx_init()`
54 *
55 * Initialise the context with an initial seed.
56 *
57 * - `br_xxx_generate()`
58 *
59 * Produce some pseudo-random bytes.
60 *
61 * - `br_xxx_update()`
62 *
63 * Inject some additional seed.
64 *
65 * The initialisation function sets the first context field (`vtable`)
66 * to a pointer to the vtable that supports the OOP API. The OOP API
67 * provides access to the same functions through function pointers,
68 * named `init()`, `generate()` and `update()`.
69 *
70 * Note that the context initialisation method may accept additional
71 * parameters, provided as a 'const void *' pointer at API level. These
72 * additional parameters depend on the implemented PRNG.
73 *
74 *
75 * ## HMAC_DRBG
76 *
77 * HMAC_DRBG is defined in [NIST SP 800-90A Revision
78 * 1](http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf).
79 * It uses HMAC repeatedly, over some configurable underlying hash
80 * function. In BearSSL, it is implemented under the "`hmac_drbg`" name.
81 * The "extra parameters" pointer for context initialisation should be
82 * set to a pointer to the vtable for the underlying hash function (e.g.
83 * pointer to `br_sha256_vtable` to use HMAC_DRBG with SHA-256).
84 *
85 * According to the NIST standard, each request shall produce up to
86 * 2<sup>19</sup> bits (i.e. 64 kB of data); moreover, the context shall
87 * be reseeded at least once every 2<sup>48</sup> requests. This
88 * implementation does not maintain the reseed counter (the threshold is
89 * too high to be reached in practice) and does not object to producing
90 * more than 64 kB in a single request; thus, the code cannot fail,
91 * which corresponds to the fact that the API has no room for error
92 * codes. However, this implies that requesting more than 64 kB in one
93 * `generate()` request, or making more than 2<sup>48</sup> requests
94 * without reseeding, is formally out of NIST specification. There is
95 * no currently known security penalty for exceeding the NIST limits,
96 * and, in any case, HMAC_DRBG usage in implementing SSL/TLS always
97 * stays much below these thresholds.
98 *
99 *
100 * ## AESCTR_DRBG
101 *
102 * AESCTR_DRBG is a custom PRNG based on AES-128 in CTR mode. This is
103 * meant to be used only in situations where you are desperate for
104 * speed, and have an hardware-optimized AES/CTR implementation. Whether
105 * this will yield perceptible improvements depends on what you use the
106 * pseudorandom bytes for, and how many you want; for instance, RSA key
107 * pair generation uses a substantial amount of randomness, and using
108 * AESCTR_DRBG instead of HMAC_DRBG yields a 15 to 20% increase in key
109 * generation speed on a recent x86 CPU (Intel Core i7-6567U at 3.30 GHz).
110 *
111 * Internally, it uses CTR mode with successive counter values, starting
112 * at zero (counter value expressed over 128 bits, big-endian convention).
113 * The counter is not allowed to reach 32768; thus, every 32768*16 bytes
114 * at most, the `update()` function is run (on an empty seed, if none is
115 * provided). The `update()` function computes the new AES-128 key by
116 * applying a custom hash function to the concatenation of a state-dependent
117 * word (encryption of an all-one block with the current key) and the new
118 * seed. The custom hash function uses Hirose's construction over AES-256;
119 * see the comments in `aesctr_drbg.c` for details.
120 *
121 * This DRBG does not follow an existing standard, and thus should be
122 * considered as inadequate for production use until it has been properly
123 * analysed.
124 */
125
126 /**
127 * \brief Class type for PRNG implementations.
128 *
129 * A `br_prng_class` instance references the methods implementing a PRNG.
130 * Constant instances of this structure are defined for each implemented
131 * PRNG. Such instances are also called "vtables".
132 */
133 typedef struct br_prng_class_ br_prng_class;
134 struct br_prng_class_ {
135 /**
136 * \brief Size (in bytes) of the context structure appropriate for
137 * running this PRNG.
138 */
139 size_t context_size;
140
141 /**
142 * \brief Initialisation method.
143 *
144 * The context to initialise is provided as a pointer to its
145 * first field (the vtable pointer); this function sets that
146 * first field to a pointer to the vtable.
147 *
148 * The extra parameters depend on the implementation; each
149 * implementation defines what kind of extra parameters it
150 * expects (if any).
151 *
152 * Requirements on the initial seed depend on the implemented
153 * PRNG.
154 *
155 * \param ctx PRNG context to initialise.
156 * \param params extra parameters for the PRNG.
157 * \param seed initial seed.
158 * \param seed_len initial seed length (in bytes).
159 */
160 void (*init)(const br_prng_class **ctx, const void *params,
161 const void *seed, size_t seed_len);
162
163 /**
164 * \brief Random bytes generation.
165 *
166 * This method produces `len` pseudorandom bytes, in the `out`
167 * buffer. The context is updated accordingly.
168 *
169 * \param ctx PRNG context.
170 * \param out output buffer.
171 * \param len number of pseudorandom bytes to produce.
172 */
173 void (*generate)(const br_prng_class **ctx, void *out, size_t len);
174
175 /**
176 * \brief Inject additional seed bytes.
177 *
178 * The provided seed bytes are added into the PRNG internal
179 * entropy pool.
180 *
181 * \param ctx PRNG context.
182 * \param seed additional seed.
183 * \param seed_len additional seed length (in bytes).
184 */
185 void (*update)(const br_prng_class **ctx,
186 const void *seed, size_t seed_len);
187 };
188
189 /**
190 * \brief Context for HMAC_DRBG.
191 *
192 * The context contents are opaque, except the first field, which
193 * supports OOP.
194 */
195 typedef struct {
196 /**
197 * \brief Pointer to the vtable.
198 *
199 * This field is set with the initialisation method/function.
200 */
201 const br_prng_class *vtable;
202 #ifndef BR_DOXYGEN_IGNORE
203 unsigned char K[64];
204 unsigned char V[64];
205 const br_hash_class *digest_class;
206 #endif
207 } br_hmac_drbg_context;
208
209 /**
210 * \brief Statically allocated, constant vtable for HMAC_DRBG.
211 */
212 extern const br_prng_class br_hmac_drbg_vtable;
213
214 /**
215 * \brief HMAC_DRBG initialisation.
216 *
217 * The context to initialise is provided as a pointer to its first field
218 * (the vtable pointer); this function sets that first field to a
219 * pointer to the vtable.
220 *
221 * The `seed` value is what is called, in NIST terminology, the
222 * concatenation of the "seed", "nonce" and "personalization string", in
223 * that order.
224 *
225 * The `digest_class` parameter defines the underlying hash function.
226 * Formally, the NIST standard specifies that the hash function shall
227 * be only SHA-1 or one of the SHA-2 functions. This implementation also
228 * works with any other implemented hash function (such as MD5), but
229 * this is non-standard and therefore not recommended.
230 *
231 * \param ctx HMAC_DRBG context to initialise.
232 * \param digest_class vtable for the underlying hash function.
233 * \param seed initial seed.
234 * \param seed_len initial seed length (in bytes).
235 */
236 void br_hmac_drbg_init(br_hmac_drbg_context *ctx,
237 const br_hash_class *digest_class, const void *seed, size_t seed_len);
238
239 /**
240 * \brief Random bytes generation with HMAC_DRBG.
241 *
242 * This method produces `len` pseudorandom bytes, in the `out`
243 * buffer. The context is updated accordingly. Formally, requesting
244 * more than 65536 bytes in one request falls out of specification
245 * limits (but it won't fail).
246 *
247 * \param ctx HMAC_DRBG context.
248 * \param out output buffer.
249 * \param len number of pseudorandom bytes to produce.
250 */
251 void br_hmac_drbg_generate(br_hmac_drbg_context *ctx, void *out, size_t len);
252
253 /**
254 * \brief Inject additional seed bytes in HMAC_DRBG.
255 *
256 * The provided seed bytes are added into the HMAC_DRBG internal
257 * entropy pool. The process does not _replace_ existing entropy,
258 * thus pushing non-random bytes (i.e. bytes which are known to the
259 * attackers) does not degrade the overall quality of generated bytes.
260 *
261 * \param ctx HMAC_DRBG context.
262 * \param seed additional seed.
263 * \param seed_len additional seed length (in bytes).
264 */
265 void br_hmac_drbg_update(br_hmac_drbg_context *ctx,
266 const void *seed, size_t seed_len);
267
268 /**
269 * \brief Get the hash function implementation used by a given instance of
270 * HMAC_DRBG.
271 *
272 * This calls MUST NOT be performed on a context which was not
273 * previously initialised.
274 *
275 * \param ctx HMAC_DRBG context.
276 * \return the hash function vtable.
277 */
278 static inline const br_hash_class *
279 br_hmac_drbg_get_hash(const br_hmac_drbg_context *ctx)
280 {
281 return ctx->digest_class;
282 }
283
284 /**
285 * \brief Type for a provider of entropy seeds.
286 *
287 * A "seeder" is a function that is able to obtain random values from
288 * some source and inject them as entropy seed in a PRNG. A seeder
289 * shall guarantee that the total entropy of the injected seed is large
290 * enough to seed a PRNG for purposes of cryptographic key generation
291 * (i.e. at least 128 bits).
292 *
293 * A seeder may report a failure to obtain adequate entropy. Seeders
294 * shall endeavour to fix themselves transient errors by trying again;
295 * thus, callers may consider reported errors as permanent.
296 *
297 * \param ctx PRNG context to seed.
298 * \return 1 on success, 0 on error.
299 */
300 typedef int (*br_prng_seeder)(const br_prng_class **ctx);
301
302 /**
303 * \brief Get a seeder backed by the operating system or hardware.
304 *
305 * Get a seeder that feeds on RNG facilities provided by the current
306 * operating system or hardware. If no such facility is known, then 0
307 * is returned.
308 *
309 * If `name` is not `NULL`, then `*name` is set to a symbolic string
310 * that identifies the seeder implementation. If no seeder is returned
311 * and `name` is not `NULL`, then `*name` is set to a pointer to the
312 * constant string `"none"`.
313 *
314 * \param name receiver for seeder name, or `NULL`.
315 * \return the system seeder, if available, or 0.
316 */
317 br_prng_seeder br_prng_seeder_system(const char **name);
318
319 /**
320 * \brief Context for AESCTR_DRBG.
321 *
322 * The context contents are opaque, except the first field, which
323 * supports OOP.
324 */
325 typedef struct {
326 /**
327 * \brief Pointer to the vtable.
328 *
329 * This field is set with the initialisation method/function.
330 */
331 const br_prng_class *vtable;
332 #ifndef BR_DOXYGEN_IGNORE
333 br_aes_gen_ctr_keys sk;
334 uint32_t cc;
335 #endif
336 } br_aesctr_drbg_context;
337
338 /**
339 * \brief Statically allocated, constant vtable for AESCTR_DRBG.
340 */
341 extern const br_prng_class br_aesctr_drbg_vtable;
342
343 /**
344 * \brief AESCTR_DRBG initialisation.
345 *
346 * The context to initialise is provided as a pointer to its first field
347 * (the vtable pointer); this function sets that first field to a
348 * pointer to the vtable.
349 *
350 * The internal AES key is first set to the all-zero key; then, the
351 * `br_aesctr_drbg_update()` function is called with the provided `seed`.
352 * The call is performed even if the seed length (`seed_len`) is zero.
353 *
354 * The `aesctr` parameter defines the underlying AES/CTR implementation.
355 *
356 * \param ctx HMAC_DRBG context to initialise.
357 * \param digest_class vtable for the underlying hash function.
358 * \param seed initial seed (can be `NULL` if `seed_len` is zero).
359 * \param seed_len initial seed length (in bytes).
360 */
361 void br_aesctr_drbg_init(br_aesctr_drbg_context *ctx,
362 const br_block_ctr_class *aesctr, const void *seed, size_t seed_len);
363
364 /**
365 * \brief Random bytes generation with AESCTR_DRBG.
366 *
367 * This method produces `len` pseudorandom bytes, in the `out`
368 * buffer. The context is updated accordingly.
369 *
370 * \param ctx AESCTR_DRBG context.
371 * \param out output buffer.
372 * \param len number of pseudorandom bytes to produce.
373 */
374 void br_aesctr_drbg_generate(br_aesctr_drbg_context *ctx,
375 void *out, size_t len);
376
377 /**
378 * \brief Inject additional seed bytes in AESCTR_DRBG.
379 *
380 * The provided seed bytes are added into the AESCTR_DRBG internal
381 * entropy pool. The process does not _replace_ existing entropy,
382 * thus pushing non-random bytes (i.e. bytes which are known to the
383 * attackers) does not degrade the overall quality of generated bytes.
384 *
385 * \param ctx AESCTR_DRBG context.
386 * \param seed additional seed.
387 * \param seed_len additional seed length (in bytes).
388 */
389 void br_aesctr_drbg_update(br_aesctr_drbg_context *ctx,
390 const void *seed, size_t seed_len);
391
392 #ifdef __cplusplus
393 }
394 #endif
395
396 #endif