1 /**
2  * \file hmac_drbg.h
3  *
4  * \brief The HMAC_DRBG pseudorandom generator.
5  *
6  * This module implements the HMAC_DRBG pseudorandom generator described
7  * in <em>NIST SP 800-90A: Recommendation for Random Number Generation Using
8  * Deterministic Random Bit Generators</em>.
9  */
10 /*
11  *  Copyright The Mbed TLS Contributors
12  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
13  */
14 #ifndef MBEDTLS_HMAC_DRBG_H
15 #define MBEDTLS_HMAC_DRBG_H
16 #include "mbedtls/private_access.h"
17 
18 #include "mbedtls/build_info.h"
19 
20 #include "mbedtls/md.h"
21 
22 #if defined(MBEDTLS_THREADING_C)
23 #include "mbedtls/threading.h"
24 #endif
25 
26 /*
27  * Error codes
28  */
29 /** Too many random requested in single call. */
30 #define MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG              -0x0003
31 /** Input too large (Entropy + additional). */
32 #define MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG                -0x0005
33 /** Read/write error in file. */
34 #define MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR                -0x0007
35 /** The entropy source failed. */
36 #define MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED        -0x0009
37 
38 /**
39  * \name SECTION: Module settings
40  *
41  * The configuration options you can set for this module are in this section.
42  * Either change them in mbedtls_config.h or define them on the compiler command line.
43  * \{
44  */
45 
46 #if !defined(MBEDTLS_HMAC_DRBG_RESEED_INTERVAL)
47 #define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL   10000   /**< Interval before reseed is performed by default */
48 #endif
49 
50 #if !defined(MBEDTLS_HMAC_DRBG_MAX_INPUT)
51 #define MBEDTLS_HMAC_DRBG_MAX_INPUT         256     /**< Maximum number of additional input bytes */
52 #endif
53 
54 #if !defined(MBEDTLS_HMAC_DRBG_MAX_REQUEST)
55 #define MBEDTLS_HMAC_DRBG_MAX_REQUEST       1024    /**< Maximum number of requested bytes per call */
56 #endif
57 
58 #if !defined(MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT)
59 #define MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT    384     /**< Maximum size of (re)seed buffer */
60 #endif
61 
62 /** \} name SECTION: Module settings */
63 
64 #define MBEDTLS_HMAC_DRBG_PR_OFF   0   /**< No prediction resistance       */
65 #define MBEDTLS_HMAC_DRBG_PR_ON    1   /**< Prediction resistance enabled  */
66 
67 #ifdef __cplusplus
68 extern "C" {
69 #endif
70 
71 /**
72  * HMAC_DRBG context.
73  */
74 typedef struct mbedtls_hmac_drbg_context {
75     /* Working state: the key K is not stored explicitly,
76      * but is implied by the HMAC context */
77     mbedtls_md_context_t MBEDTLS_PRIVATE(md_ctx);                    /*!< HMAC context (inc. K)  */
78     unsigned char MBEDTLS_PRIVATE(V)[MBEDTLS_MD_MAX_SIZE];  /*!< V in the spec          */
79     int MBEDTLS_PRIVATE(reseed_counter);                     /*!< reseed counter         */
80 
81     /* Administrative state */
82     size_t MBEDTLS_PRIVATE(entropy_len);         /*!< entropy bytes grabbed on each (re)seed */
83     int MBEDTLS_PRIVATE(prediction_resistance);  /*!< enable prediction resistance (Automatic
84                                                     reseed before every random generation) */
85     int MBEDTLS_PRIVATE(reseed_interval);        /*!< reseed interval   */
86 
87     /* Callbacks */
88     int(*MBEDTLS_PRIVATE(f_entropy))(void *, unsigned char *, size_t);  /*!< entropy function */
89     void *MBEDTLS_PRIVATE(p_entropy);            /*!< context for the entropy function        */
90 
91 #if defined(MBEDTLS_THREADING_C)
92     /* Invariant: the mutex is initialized if and only if
93      * md_ctx->md_info != NULL. This means that the mutex is initialized
94      * during the initial seeding in mbedtls_hmac_drbg_seed() or
95      * mbedtls_hmac_drbg_seed_buf() and freed in mbedtls_ctr_drbg_free().
96      *
97      * Note that this invariant may change without notice. Do not rely on it
98      * and do not access the mutex directly in application code.
99      */
100     mbedtls_threading_mutex_t MBEDTLS_PRIVATE(mutex);
101 #endif
102 } mbedtls_hmac_drbg_context;
103 
104 /**
105  * \brief               HMAC_DRBG context initialization.
106  *
107  * This function makes the context ready for mbedtls_hmac_drbg_seed(),
108  * mbedtls_hmac_drbg_seed_buf() or mbedtls_hmac_drbg_free().
109  *
110  * \note                The reseed interval is #MBEDTLS_HMAC_DRBG_RESEED_INTERVAL
111  *                      by default. Override this value by calling
112  *                      mbedtls_hmac_drbg_set_reseed_interval().
113  *
114  * \param ctx           HMAC_DRBG context to be initialized.
115  */
116 void mbedtls_hmac_drbg_init(mbedtls_hmac_drbg_context *ctx);
117 
118 /**
119  * \brief               HMAC_DRBG initial seeding.
120  *
121  * Set the initial seed and set up the entropy source for future reseeds.
122  *
123  * A typical choice for the \p f_entropy and \p p_entropy parameters is
124  * to use the entropy module:
125  * - \p f_entropy is mbedtls_entropy_func();
126  * - \p p_entropy is an instance of ::mbedtls_entropy_context initialized
127  *   with mbedtls_entropy_init() (which registers the platform's default
128  *   entropy sources).
129  *
130  * You can provide a personalization string in addition to the
131  * entropy source, to make this instantiation as unique as possible.
132  *
133  * \note                By default, the security strength as defined by NIST is:
134  *                      - 128 bits if \p md_info is SHA-1;
135  *                      - 192 bits if \p md_info is SHA-224;
136  *                      - 256 bits if \p md_info is SHA-256, SHA-384 or SHA-512.
137  *                      Note that SHA-256 is just as efficient as SHA-224.
138  *                      The security strength can be reduced if a smaller
139  *                      entropy length is set with
140  *                      mbedtls_hmac_drbg_set_entropy_len().
141  *
142  * \note                The default entropy length is the security strength
143  *                      (converted from bits to bytes). You can override
144  *                      it by calling mbedtls_hmac_drbg_set_entropy_len().
145  *
146  * \note                During the initial seeding, this function calls
147  *                      the entropy source to obtain a nonce
148  *                      whose length is half the entropy length.
149  */
150 #if defined(MBEDTLS_THREADING_C)
151 /**
152  * \note                When Mbed TLS is built with threading support,
153  *                      after this function returns successfully,
154  *                      it is safe to call mbedtls_hmac_drbg_random()
155  *                      from multiple threads. Other operations, including
156  *                      reseeding, are not thread-safe.
157  */
158 #endif /* MBEDTLS_THREADING_C */
159 /**
160  * \param ctx           HMAC_DRBG context to be seeded.
161  * \param md_info       MD algorithm to use for HMAC_DRBG.
162  * \param f_entropy     The entropy callback, taking as arguments the
163  *                      \p p_entropy context, the buffer to fill, and the
164  *                      length of the buffer.
165  *                      \p f_entropy is always called with a length that is
166  *                      less than or equal to the entropy length.
167  * \param p_entropy     The entropy context to pass to \p f_entropy.
168  * \param custom        The personalization string.
169  *                      This can be \c NULL, in which case the personalization
170  *                      string is empty regardless of the value of \p len.
171  * \param len           The length of the personalization string.
172  *                      This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT
173  *                      and also at most
174  *                      #MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT - \c entropy_len * 3 / 2
175  *                      where \c entropy_len is the entropy length
176  *                      described above.
177  *
178  * \return              \c 0 if successful.
179  * \return              #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info is
180  *                      invalid.
181  * \return              #MBEDTLS_ERR_MD_ALLOC_FAILED if there was not enough
182  *                      memory to allocate context data.
183  * \return              #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED
184  *                      if the call to \p f_entropy failed.
185  */
186 int mbedtls_hmac_drbg_seed(mbedtls_hmac_drbg_context *ctx,
187                            const mbedtls_md_info_t *md_info,
188                            int (*f_entropy)(void *, unsigned char *, size_t),
189                            void *p_entropy,
190                            const unsigned char *custom,
191                            size_t len);
192 
193 /**
194  * \brief               Initialisation of simplified HMAC_DRBG (never reseeds).
195  *
196  * This function is meant for use in algorithms that need a pseudorandom
197  * input such as deterministic ECDSA.
198  */
199 #if defined(MBEDTLS_THREADING_C)
200 /**
201  * \note                When Mbed TLS is built with threading support,
202  *                      after this function returns successfully,
203  *                      it is safe to call mbedtls_hmac_drbg_random()
204  *                      from multiple threads. Other operations, including
205  *                      reseeding, are not thread-safe.
206  */
207 #endif /* MBEDTLS_THREADING_C */
208 /**
209  * \param ctx           HMAC_DRBG context to be initialised.
210  * \param md_info       MD algorithm to use for HMAC_DRBG.
211  * \param data          Concatenation of the initial entropy string and
212  *                      the additional data.
213  * \param data_len      Length of \p data in bytes.
214  *
215  * \return              \c 0 if successful. or
216  * \return              #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info is
217  *                      invalid.
218  * \return              #MBEDTLS_ERR_MD_ALLOC_FAILED if there was not enough
219  *                      memory to allocate context data.
220  */
221 int mbedtls_hmac_drbg_seed_buf(mbedtls_hmac_drbg_context *ctx,
222                                const mbedtls_md_info_t *md_info,
223                                const unsigned char *data, size_t data_len);
224 
225 /**
226  * \brief               This function turns prediction resistance on or off.
227  *                      The default value is off.
228  *
229  * \note                If enabled, entropy is gathered at the beginning of
230  *                      every call to mbedtls_hmac_drbg_random_with_add()
231  *                      or mbedtls_hmac_drbg_random().
232  *                      Only use this if your entropy source has sufficient
233  *                      throughput.
234  *
235  * \param ctx           The HMAC_DRBG context.
236  * \param resistance    #MBEDTLS_HMAC_DRBG_PR_ON or #MBEDTLS_HMAC_DRBG_PR_OFF.
237  */
238 void mbedtls_hmac_drbg_set_prediction_resistance(mbedtls_hmac_drbg_context *ctx,
239                                                  int resistance);
240 
241 /**
242  * \brief               This function sets the amount of entropy grabbed on each
243  *                      seed or reseed.
244  *
245  * See the documentation of mbedtls_hmac_drbg_seed() for the default value.
246  *
247  * \param ctx           The HMAC_DRBG context.
248  * \param len           The amount of entropy to grab, in bytes.
249  */
250 void mbedtls_hmac_drbg_set_entropy_len(mbedtls_hmac_drbg_context *ctx,
251                                        size_t len);
252 
253 /**
254  * \brief               Set the reseed interval.
255  *
256  * The reseed interval is the number of calls to mbedtls_hmac_drbg_random()
257  * or mbedtls_hmac_drbg_random_with_add() after which the entropy function
258  * is called again.
259  *
260  * The default value is #MBEDTLS_HMAC_DRBG_RESEED_INTERVAL.
261  *
262  * \param ctx           The HMAC_DRBG context.
263  * \param interval      The reseed interval.
264  */
265 void mbedtls_hmac_drbg_set_reseed_interval(mbedtls_hmac_drbg_context *ctx,
266                                            int interval);
267 
268 /**
269  * \brief               This function updates the state of the HMAC_DRBG context.
270  *
271  * \note                This function is not thread-safe. It is not safe
272  *                      to call this function if another thread might be
273  *                      concurrently obtaining random numbers from the same
274  *                      context or updating or reseeding the same context.
275  *
276  * \param ctx           The HMAC_DRBG context.
277  * \param additional    The data to update the state with.
278  *                      If this is \c NULL, there is no additional data.
279  * \param add_len       Length of \p additional in bytes.
280  *                      Unused if \p additional is \c NULL.
281  *
282  * \return              \c 0 on success, or an error from the underlying
283  *                      hash calculation.
284  */
285 int mbedtls_hmac_drbg_update(mbedtls_hmac_drbg_context *ctx,
286                              const unsigned char *additional, size_t add_len);
287 
288 /**
289  * \brief               This function reseeds the HMAC_DRBG context, that is
290  *                      extracts data from the entropy source.
291  *
292  * \note                This function is not thread-safe. It is not safe
293  *                      to call this function if another thread might be
294  *                      concurrently obtaining random numbers from the same
295  *                      context or updating or reseeding the same context.
296  *
297  * \param ctx           The HMAC_DRBG context.
298  * \param additional    Additional data to add to the state.
299  *                      If this is \c NULL, there is no additional data
300  *                      and \p len should be \c 0.
301  * \param len           The length of the additional data.
302  *                      This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT
303  *                      and also at most
304  *                      #MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT - \c entropy_len
305  *                      where \c entropy_len is the entropy length
306  *                      (see mbedtls_hmac_drbg_set_entropy_len()).
307  *
308  * \return              \c 0 if successful.
309  * \return              #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED
310  *                      if a call to the entropy function failed.
311  */
312 int mbedtls_hmac_drbg_reseed(mbedtls_hmac_drbg_context *ctx,
313                              const unsigned char *additional, size_t len);
314 
315 /**
316  * \brief   This function updates an HMAC_DRBG instance with additional
317  *          data and uses it to generate random data.
318  *
319  * This function automatically reseeds if the reseed counter is exceeded
320  * or prediction resistance is enabled.
321  *
322  * \note                This function is not thread-safe. It is not safe
323  *                      to call this function if another thread might be
324  *                      concurrently obtaining random numbers from the same
325  *                      context or updating or reseeding the same context.
326  *
327  * \param p_rng         The HMAC_DRBG context. This must be a pointer to a
328  *                      #mbedtls_hmac_drbg_context structure.
329  * \param output        The buffer to fill.
330  * \param output_len    The length of the buffer in bytes.
331  *                      This must be at most #MBEDTLS_HMAC_DRBG_MAX_REQUEST.
332  * \param additional    Additional data to update with.
333  *                      If this is \c NULL, there is no additional data
334  *                      and \p add_len should be \c 0.
335  * \param add_len       The length of the additional data.
336  *                      This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT.
337  *
338  * \return              \c 0 if successful.
339  * \return              #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED
340  *                      if a call to the entropy source failed.
341  * \return              #MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG if
342  *                      \p output_len > #MBEDTLS_HMAC_DRBG_MAX_REQUEST.
343  * \return              #MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG if
344  *                      \p add_len > #MBEDTLS_HMAC_DRBG_MAX_INPUT.
345  */
346 int mbedtls_hmac_drbg_random_with_add(void *p_rng,
347                                       unsigned char *output, size_t output_len,
348                                       const unsigned char *additional,
349                                       size_t add_len);
350 
351 /**
352  * \brief   This function uses HMAC_DRBG to generate random data.
353  *
354  * This function automatically reseeds if the reseed counter is exceeded
355  * or prediction resistance is enabled.
356  */
357 #if defined(MBEDTLS_THREADING_C)
358 /**
359  * \note                When Mbed TLS is built with threading support,
360  *                      it is safe to call mbedtls_ctr_drbg_random()
361  *                      from multiple threads. Other operations, including
362  *                      reseeding, are not thread-safe.
363  */
364 #endif /* MBEDTLS_THREADING_C */
365 /**
366  * \param p_rng         The HMAC_DRBG context. This must be a pointer to a
367  *                      #mbedtls_hmac_drbg_context structure.
368  * \param output        The buffer to fill.
369  * \param out_len       The length of the buffer in bytes.
370  *                      This must be at most #MBEDTLS_HMAC_DRBG_MAX_REQUEST.
371  *
372  * \return              \c 0 if successful.
373  * \return              #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED
374  *                      if a call to the entropy source failed.
375  * \return              #MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG if
376  *                      \p out_len > #MBEDTLS_HMAC_DRBG_MAX_REQUEST.
377  */
378 int mbedtls_hmac_drbg_random(void *p_rng, unsigned char *output, size_t out_len);
379 
380 /**
381  * \brief               This function resets HMAC_DRBG context to the state immediately
382  *                      after initial call of mbedtls_hmac_drbg_init().
383  *
384  * \param ctx           The HMAC_DRBG context to free.
385  */
386 void mbedtls_hmac_drbg_free(mbedtls_hmac_drbg_context *ctx);
387 
388 #if defined(MBEDTLS_FS_IO)
389 /**
390  * \brief               This function writes a seed file.
391  *
392  * \param ctx           The HMAC_DRBG context.
393  * \param path          The name of the file.
394  *
395  * \return              \c 0 on success.
396  * \return              #MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR on file error.
397  * \return              #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED on reseed
398  *                      failure.
399  */
400 int mbedtls_hmac_drbg_write_seed_file(mbedtls_hmac_drbg_context *ctx, const char *path);
401 
402 /**
403  * \brief               This function reads and updates a seed file. The seed
404  *                      is added to this instance.
405  *
406  * \param ctx           The HMAC_DRBG context.
407  * \param path          The name of the file.
408  *
409  * \return              \c 0 on success.
410  * \return              #MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR on file error.
411  * \return              #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED on
412  *                      reseed failure.
413  * \return              #MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG if the existing
414  *                      seed file is too large.
415  */
416 int mbedtls_hmac_drbg_update_seed_file(mbedtls_hmac_drbg_context *ctx, const char *path);
417 #endif /* MBEDTLS_FS_IO */
418 
419 
420 #if defined(MBEDTLS_SELF_TEST)
421 /**
422  * \brief               The HMAC_DRBG Checkup routine.
423  *
424  * \return              \c 0 if successful.
425  * \return              \c 1 if the test failed.
426  */
427 int mbedtls_hmac_drbg_self_test(int verbose);
428 #endif
429 
430 #ifdef __cplusplus
431 }
432 #endif
433 
434 #endif /* hmac_drbg.h */
435