1 /* random-drbg.c - Deterministic Random Bits Generator
2  * Copyright 2014 Stephan Mueller <smueller@chronox.de>
3  *
4  * DRBG: Deterministic Random Bits Generator
5  *       Based on NIST Recommended DRBG from NIST SP800-90A with the following
6  *       properties:
7  *		* CTR DRBG with DF with AES-128, AES-192, AES-256 cores
8  * 		* Hash DRBG with DF with SHA-1, SHA-256, SHA-384, SHA-512 cores
9  * 		* HMAC DRBG with DF with SHA-1, SHA-256, SHA-384, SHA-512 cores
10  * 		* with and without prediction resistance
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, and the entire permission notice in its entirety,
17  *    including the disclaimer of warranties.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. The name of the author may not be used to endorse or promote
22  *    products derived from this software without specific prior
23  *    written permission.
24  *
25  * ALTERNATIVELY, this product may be distributed under the terms of
26  * LGPLv2+, in which case the provisions of the LGPL are
27  * required INSTEAD OF the above restrictions.  (This clause is
28  * necessary due to a potential bad interaction between the LGPL and
29  * the restrictions contained in a BSD-style copyright.)
30  *
31  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
32  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
34  * WHICH ARE HEREBY DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE
35  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
36  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
37  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
38  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
39  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
41  * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
42  * DAMAGE.
43  *
44  *
45  * gcry_control GCRYCTL_DRBG_REINIT
46  * ================================
47  * This control request re-initializes the DRBG completely, i.e. the entire
48  * state of the DRBG is zeroized (with two exceptions listed in
49  * GCRYCTL_DRBG_SET_ENTROPY).
50  *
51  * The control request takes the following values which influences how
52  * the DRBG is re-initialized:
53  *
54  *  - const char *flagstr
55  *
56  *      This variable specifies the DRBG type to be used for the next
57  *	initialization.  If set to NULL, the previous DRBG type is
58  *	used for the initialization.  If not NULL a space separated
59  *	list of tokens with associated flag values is expected which
60  *	are ORed to form the mandatory flags of the requested DRBG
61  *	strength and cipher type.  Optionally, the prediction
62  *	resistance flag can be ORed into the flags variable.
63  *
64  *      | String token | Flag value             |
65  *      |--------------+------------------------|
66  *      | aes          | DRBG_CTRAES            |
67  *      | serpent      | DRBG_CTRSERPENT        |
68  *      | twofish      | DRBG_CTRTWOFISH        |
69  *      | sha1         | DRBG_HASHSHA1          |
70  *      | sha256       | DRBG_HASHSHA256        |
71  *      | sha512       | DRBG_HASHSHA512        |
72  *      | hmac         | DRBG_HMAC              |
73  *      | sym128       | DRBG_SYM128            |
74  *      | sym192       | DRBG_SYM192            |
75  *      | sym256       | DRBG_SYM256            |
76  *      | pr           | DRBG_PREDICTION_RESIST |
77  *
78  *    For example:
79  *
80  * 	- CTR-DRBG with AES-128 without prediction resistance:
81  * 	    "aes sym128"
82  * 	- HMAC-DRBG with SHA-512 with prediction resistance:
83  * 	    "hmac sha512 pr"
84  *
85  *  - gcry_buffer_t *pers
86  *
87  *      NULL terminated array with personalization strings to be used
88  *	for initialization.
89  *
90  *  - int npers
91  *
92  *     Size of PERS.
93  *
94  *  - void *guard
95  *
96  *      A value of NULL must be passed for this.
97  *
98  * The variable of flags is independent from the pers/perslen variables. If
99  * flags is set to 0 and perslen is set to 0, the current DRBG type is
100  * completely reset without using a personalization string.
101  *
102  * DRBG Usage
103  * ==========
104  * The SP 800-90A DRBG allows the user to specify a personalization string
105  * for initialization as well as an additional information string for each
106  * random number request.  The following code fragments show how a caller
107  * uses the API to use the full functionality of the DRBG.
108  *
109  * Usage without any additional data
110  * ---------------------------------
111  * gcry_randomize(outbuf, OUTLEN, GCRY_STRONG_RANDOM);
112  *
113  *
114  * Usage with personalization string during initialization
115  * -------------------------------------------------------
116  * drbg_string_t pers;
117  * char personalization[11] = "some-string";
118  *
119  * drbg_string_fill(&pers, personalization, strlen(personalization));
120  * // The reset completely re-initializes the DRBG with the provided
121  * // personalization string without changing the DRBG type
122  * ret = gcry_control(GCRYCTL_DRBG_REINIT, 0, &pers);
123  * gcry_randomize(outbuf, OUTLEN, GCRY_STRONG_RANDOM);
124  *
125  *
126  * Usage with additional information string during random number request
127  * ---------------------------------------------------------------------
128  * drbg_string_t addtl;
129  * char addtl_string[11] = "some-string";
130  *
131  * drbg_string_fill(&addtl, addtl_string, strlen(addtl_string));
132  * // The following call is a wrapper to gcry_randomize() and returns
133  * // the same error codes.
134  * gcry_randomize_drbg(outbuf, OUTLEN, GCRY_STRONG_RANDOM, &addtl);
135  *
136  *
137  * Usage with personalization and additional information strings
138  * -------------------------------------------------------------
139  * Just mix both scenarios above.
140  *
141  *
142  * Switch the DRBG type to some other type
143  * ---------------------------------------
144  * // Switch to CTR DRBG AES-128 without prediction resistance
145  * ret = gcry_control(GCRYCTL_DRBG_REINIT, DRBG_NOPR_CTRAES128, NULL);
146  * gcry_randomize(outbuf, OUTLEN, GCRY_STRONG_RANDOM);
147  */
148 
149 #include <config.h>
150 
151 #include <string.h>
152 #include <unistd.h>
153 #include <stdint.h>
154 
155 #include "g10lib.h"
156 #include "random.h"
157 #include "rand-internal.h"
158 #include "../cipher/bufhelp.h"
159 
160 
161 
162 /******************************************************************
163  * Constants
164  ******************************************************************/
165 
166 /*
167  * DRBG flags bitmasks
168  *
169  * 31 (B) 28      19         (A)         0
170  *  +-+-+-+--------+---+-----------+-----+
171  *  |~|~|u|~~~~~~~~| 3 |     2     |  1  |
172  *  +-+-+-+--------+- -+-----------+-----+
173  * ctl flg|        |drbg use selection flags
174  *
175  */
176 
177 /* Internal state control flags (B) */
178 #define DRBG_PREDICTION_RESIST	((u32)1<<28)
179 
180 /* CTR type modifiers (A.1)*/
181 #define DRBG_CTRAES		((u32)1<<0)
182 #define DRBG_CTRSERPENT		((u32)1<<1)
183 #define DRBG_CTRTWOFISH		((u32)1<<2)
184 #define DRBG_CTR_MASK	        (DRBG_CTRAES | DRBG_CTRSERPENT \
185                                  | DRBG_CTRTWOFISH)
186 
187 /* HASH type modifiers (A.2)*/
188 #define DRBG_HASHSHA1		((u32)1<<4)
189 #define DRBG_HASHSHA224		((u32)1<<5)
190 #define DRBG_HASHSHA256		((u32)1<<6)
191 #define DRBG_HASHSHA384		((u32)1<<7)
192 #define DRBG_HASHSHA512		((u32)1<<8)
193 #define DRBG_HASH_MASK		(DRBG_HASHSHA1 | DRBG_HASHSHA224 \
194 				 | DRBG_HASHSHA256 | DRBG_HASHSHA384 \
195 				 | DRBG_HASHSHA512)
196 /* type modifiers (A.3)*/
197 #define DRBG_HMAC		((u32)1<<12)
198 #define DRBG_SYM128		((u32)1<<13)
199 #define DRBG_SYM192		((u32)1<<14)
200 #define DRBG_SYM256		((u32)1<<15)
201 #define DRBG_TYPE_MASK		(DRBG_HMAC | DRBG_SYM128 | DRBG_SYM192 \
202 				 | DRBG_SYM256)
203 #define DRBG_CIPHER_MASK        (DRBG_CTR_MASK | DRBG_HASH_MASK \
204                                  | DRBG_TYPE_MASK)
205 
206 #define DRBG_PR_CTRAES128   (DRBG_PREDICTION_RESIST | DRBG_CTRAES | DRBG_SYM128)
207 #define DRBG_PR_CTRAES192   (DRBG_PREDICTION_RESIST | DRBG_CTRAES | DRBG_SYM192)
208 #define DRBG_PR_CTRAES256   (DRBG_PREDICTION_RESIST | DRBG_CTRAES | DRBG_SYM256)
209 #define DRBG_NOPR_CTRAES128 (DRBG_CTRAES | DRBG_SYM128)
210 #define DRBG_NOPR_CTRAES192 (DRBG_CTRAES | DRBG_SYM192)
211 #define DRBG_NOPR_CTRAES256 (DRBG_CTRAES | DRBG_SYM256)
212 #define DRBG_PR_HASHSHA1     (DRBG_PREDICTION_RESIST | DRBG_HASHSHA1)
213 #define DRBG_PR_HASHSHA256   (DRBG_PREDICTION_RESIST | DRBG_HASHSHA256)
214 #define DRBG_PR_HASHSHA384   (DRBG_PREDICTION_RESIST | DRBG_HASHSHA384)
215 #define DRBG_PR_HASHSHA512   (DRBG_PREDICTION_RESIST | DRBG_HASHSHA512)
216 #define DRBG_NOPR_HASHSHA1   (DRBG_HASHSHA1)
217 #define DRBG_NOPR_HASHSHA256 (DRBG_HASHSHA256)
218 #define DRBG_NOPR_HASHSHA384 (DRBG_HASHSHA384)
219 #define DRBG_NOPR_HASHSHA512 (DRBG_HASHSHA512)
220 #define DRBG_PR_HMACSHA1     (DRBG_PREDICTION_RESIST | DRBG_HASHSHA1 \
221                               | DRBG_HMAC)
222 #define DRBG_PR_HMACSHA256   (DRBG_PREDICTION_RESIST | DRBG_HASHSHA256 \
223                               | DRBG_HMAC)
224 #define DRBG_PR_HMACSHA384   (DRBG_PREDICTION_RESIST | DRBG_HASHSHA384 \
225                               | DRBG_HMAC)
226 #define DRBG_PR_HMACSHA512   (DRBG_PREDICTION_RESIST | DRBG_HASHSHA512 \
227                               | DRBG_HMAC)
228 #define DRBG_NOPR_HMACSHA1   (DRBG_HASHSHA1 | DRBG_HMAC)
229 #define DRBG_NOPR_HMACSHA256 (DRBG_HASHSHA256 | DRBG_HMAC)
230 #define DRBG_NOPR_HMACSHA384 (DRBG_HASHSHA384 | DRBG_HMAC)
231 #define DRBG_NOPR_HMACSHA512 (DRBG_HASHSHA512 | DRBG_HMAC)
232 
233 
234 /* The default DRGB type.  */
235 #define DRBG_DEFAULT_TYPE    DRBG_NOPR_HMACSHA256
236 
237 
238 #define DRBG_CTR_NULL_LEN 128
239 
240 
241 /******************************************************************
242  * Common data structures
243  ******************************************************************/
244 
245 /*
246  * SP800-90A requires the concatenation of different data. To avoid copying
247  * buffers around or allocate additional memory, the following data structure
248  * is used to point to the original memory with its size. In addition, it
249  * is used to build a linked list. The linked list defines the concatenation
250  * of individual buffers. The order of memory block referenced in that
251  * linked list determines the order of concatenation.
252  */
253 struct drbg_string_s
254 {
255   const unsigned char *buf;
256   size_t len;
257   struct drbg_string_s *next;
258 };
259 typedef struct drbg_string_s drbg_string_t;
260 
261 
262 /* DRBG input data structure for DRBG generate with additional
263  * information string.  */
264 struct drbg_gen_s
265 {
266   unsigned char *outbuf;	/* output buffer for random numbers */
267   unsigned int outlen;	        /* size of output buffer */
268   drbg_string_t *addtl;	        /* input buffer for
269 				 * additional information string */
270 };
271 typedef struct drbg_gen_s drbg_gen_t;
272 
273 
274 /* Forward declaration of the state object pointer.  */
275 struct drbg_state_s;
276 typedef struct drbg_state_s *drbg_state_t;
277 
278 
279 struct drbg_core_s
280 {
281   u32 flags;			/* flags for the cipher */
282   ushort statelen;		/* maximum state length */
283   ushort blocklen_bytes;	/* block size of output in bytes */
284   int backend_cipher;		/* libgcrypt backend cipher */
285 };
286 
287 struct drbg_state_ops_s
288 {
289   gpg_err_code_t (*update) (drbg_state_t drbg,
290 			    drbg_string_t *seed, int reseed);
291   gpg_err_code_t (*generate) (drbg_state_t drbg,
292 			      unsigned char *buf, unsigned int buflen,
293 			      drbg_string_t *addtl);
294   gpg_err_code_t (*crypto_init) (drbg_state_t drbg);
295   void		 (*crypto_fini) (drbg_state_t drbg);
296 };
297 
298 struct drbg_test_data_s
299 {
300   drbg_string_t *testentropy;	/* TEST PARAMETER: test entropy */
301   int fail_seed_source:1;	/* If set, the seed function will
302                                  * return an error. */
303 };
304 
305 
306 /* This state object keeps the state of an DRBG instance.  */
307 struct drbg_state_s
308 {
309   unsigned char *V;		/* internal state 10.1.1.1 1a) */
310   unsigned char *C;		/* hash: static value 10.1.1.1 1b)
311 				 * hmac / ctr: key */
312   size_t reseed_ctr;		/* Number of RNG requests since last reseed --
313 				 * 10.1.1.1 1c) */
314   unsigned char *scratchpad;	/* some memory the DRBG can use for its
315 				 * operation -- allocated during init */
316   void *priv_data;		/* Cipher handle */
317   gcry_cipher_hd_t ctr_handle;	/* CTR mode cipher handle */
318   int seeded:1;			/* DRBG fully seeded? */
319   int pr:1;			/* Prediction resistance enabled? */
320   /* Taken from libgcrypt ANSI X9.31 DRNG: We need to keep track of the
321    * process which did the initialization so that we can detect a fork.
322    * The volatile modifier is required so that the compiler does not
323    * optimize it away in case the getpid function is badly attributed. */
324   pid_t seed_init_pid;
325   const struct drbg_state_ops_s *d_ops;
326   const struct drbg_core_s *core;
327   struct drbg_test_data_s *test_data;
328 };
329 
330 enum drbg_prefixes
331 {
332   DRBG_PREFIX0 = 0x00,
333   DRBG_PREFIX1,
334   DRBG_PREFIX2,
335   DRBG_PREFIX3
336 };
337 
338 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
339 
340 /***************************************************************
341  * Global variables
342  ***************************************************************/
343 
344 /* Global state variable holding the current instance of the DRBG.  */
345 static drbg_state_t drbg_state;
346 
347 /* This is the lock variable we use to serialize access to this RNG. */
348 GPGRT_LOCK_DEFINE(drbg_lock_var);
349 
350 
351 /***************************************************************
352  * Backend cipher definitions available to DRBG
353  ***************************************************************/
354 
355 static const struct drbg_core_s drbg_cores[] = {
356   /* Hash DRBGs */
357   {DRBG_HASHSHA1, 55, 20, GCRY_MD_SHA1},
358   {DRBG_HASHSHA256, 55, 32, GCRY_MD_SHA256},
359   {DRBG_HASHSHA384, 111, 48, GCRY_MD_SHA384},
360   {DRBG_HASHSHA512, 111, 64, GCRY_MD_SHA512},
361   /* HMAC DRBGs */
362   {DRBG_HASHSHA1   | DRBG_HMAC, 20, 20, GCRY_MD_SHA1},
363   {DRBG_HASHSHA256 | DRBG_HMAC, 32, 32, GCRY_MD_SHA256},
364   {DRBG_HASHSHA384 | DRBG_HMAC, 48, 48, GCRY_MD_SHA384},
365   {DRBG_HASHSHA512 | DRBG_HMAC, 64, 64, GCRY_MD_SHA512},
366   /* block ciphers */
367   {DRBG_CTRAES | DRBG_SYM128, 32, 16, GCRY_CIPHER_AES128},
368   {DRBG_CTRAES | DRBG_SYM192, 40, 16, GCRY_CIPHER_AES192},
369   {DRBG_CTRAES | DRBG_SYM256, 48, 16, GCRY_CIPHER_AES256}
370 };
371 
372 static gpg_err_code_t drbg_hash_init (drbg_state_t drbg);
373 static gpg_err_code_t drbg_hmac_init (drbg_state_t drbg);
374 static gpg_err_code_t drbg_hmac_setkey (drbg_state_t drbg,
375 					const unsigned char *key);
376 static void drbg_hash_fini (drbg_state_t drbg);
377 static byte *drbg_hash (drbg_state_t drbg, const drbg_string_t *buf);
378 static gpg_err_code_t drbg_sym_init (drbg_state_t drbg);
379 static void drbg_sym_fini (drbg_state_t drbg);
380 static gpg_err_code_t drbg_sym_setkey (drbg_state_t drbg,
381 				       const unsigned char *key);
382 static gpg_err_code_t drbg_sym (drbg_state_t drbg, unsigned char *outval,
383 				const drbg_string_t *buf);
384 static gpg_err_code_t drbg_sym_ctr (drbg_state_t drbg,
385 			const unsigned char *inbuf, unsigned int inbuflen,
386 			unsigned char *outbuf, unsigned int outbuflen);
387 
388 /******************************************************************
389  ******************************************************************
390  ******************************************************************
391  * Generic DRBG code
392  ******************************************************************
393  ******************************************************************
394  ******************************************************************/
395 
396 /******************************************************************
397  * Generic helper functions
398  ******************************************************************/
399 
400 #if 0
401 #define dbg(x) do { log_debug x; } while(0)
402 #else
403 #define dbg(x)
404 #endif
405 
406 /*
407  * Parse a string of flags and store the flag values at R_FLAGS.
408  * Return 0 on success.
409  */
410 static gpg_err_code_t
parse_flag_string(const char * string,u32 * r_flags)411 parse_flag_string (const char *string, u32 *r_flags)
412 {
413   struct {
414     const char *name;
415     u32 flag;
416   } table[] = {
417     { "aes",     DRBG_CTRAES            },
418     { "serpent", DRBG_CTRSERPENT        },
419     { "twofish", DRBG_CTRTWOFISH        },
420     { "sha1",    DRBG_HASHSHA1          },
421     { "sha256",  DRBG_HASHSHA256        },
422     { "sha512",  DRBG_HASHSHA512        },
423     { "hmac",    DRBG_HMAC              },
424     { "sym128",  DRBG_SYM128            },
425     { "sym192",  DRBG_SYM192            },
426     { "sym256",  DRBG_SYM256            },
427     { "pr",      DRBG_PREDICTION_RESIST }
428   };
429 
430   *r_flags = 0;
431   if (string)
432     {
433       char **tl;
434       const char *s;
435       int i, j;
436 
437       tl = _gcry_strtokenize (string, NULL);
438       if (!tl)
439         return gpg_err_code_from_syserror ();
440       for (i=0; (s=tl[i]); i++)
441         {
442           for (j=0; j < DIM (table); j++)
443             if (!strcmp (s, table[j].name))
444               {
445                 *r_flags |= table[j].flag;
446                 break;
447               }
448           if (!(j < DIM (table)))
449             {
450               xfree (tl);
451               return GPG_ERR_INV_FLAG;
452             }
453         }
454       xfree (tl);
455     }
456 
457   return 0;
458 }
459 
460 static inline void
drbg_string_fill(drbg_string_t * string,const unsigned char * buf,size_t len)461 drbg_string_fill (drbg_string_t *string,
462                        const unsigned char *buf, size_t len)
463 {
464   string->buf = buf;
465   string->len = len;
466   string->next = NULL;
467 }
468 
469 static inline ushort
drbg_statelen(drbg_state_t drbg)470 drbg_statelen (drbg_state_t drbg)
471 {
472   if (drbg && drbg->core)
473     return drbg->core->statelen;
474   return 0;
475 }
476 
477 static inline ushort
drbg_blocklen(drbg_state_t drbg)478 drbg_blocklen (drbg_state_t drbg)
479 {
480   if (drbg && drbg->core)
481     return drbg->core->blocklen_bytes;
482   return 0;
483 }
484 
485 static inline ushort
drbg_keylen(drbg_state_t drbg)486 drbg_keylen (drbg_state_t drbg)
487 {
488   if (drbg && drbg->core)
489     return (drbg->core->statelen - drbg->core->blocklen_bytes);
490   return 0;
491 }
492 
493 static inline size_t
drbg_max_request_bytes(void)494 drbg_max_request_bytes (void)
495 {
496   /* SP800-90A requires the limit 2**19 bits, but we return bytes */
497   return (1 << 16);
498 }
499 
500 static inline size_t
drbg_max_addtl(void)501 drbg_max_addtl (void)
502 {
503   /* SP800-90A requires 2**35 bytes additional info str / pers str */
504 #ifdef __LP64__
505   return (1UL << 35);
506 #else
507   /*
508    * SP800-90A allows smaller maximum numbers to be returned -- we
509    * return SIZE_MAX - 1 to allow the verification of the enforcement
510    * of this value in drbg_healthcheck_sanity.
511    */
512   return (SIZE_MAX - 1);
513 #endif
514 }
515 
516 static inline size_t
drbg_max_requests(void)517 drbg_max_requests (void)
518 {
519   /* SP800-90A requires 2**48 maximum requests before reseeding */
520 #ifdef __LP64__
521   return (1UL << 48);
522 #else
523   return SIZE_MAX;
524 #endif
525 }
526 
527 /*
528  * Return strength of DRBG according to SP800-90A section 8.4
529  *
530  * flags: DRBG flags reference
531  *
532  * Return: normalized strength value or 32 as a default to counter
533  * 	   programming errors
534  */
535 static inline unsigned short
drbg_sec_strength(u32 flags)536 drbg_sec_strength (u32 flags)
537 {
538   if ((flags & DRBG_HASHSHA1) || (flags & DRBG_SYM128))
539     return 16;
540   else if (flags & DRBG_SYM192)
541     return 24;
542   else if ((flags & DRBG_SYM256) || (flags & DRBG_HASHSHA256) ||
543 	   (flags & DRBG_HASHSHA384) || (flags & DRBG_HASHSHA512))
544     return 32;
545   else
546     return 32;
547 }
548 
549 static void
drbg_add_buf(unsigned char * dst,size_t dstlen,unsigned char * add,size_t addlen)550 drbg_add_buf (unsigned char *dst, size_t dstlen,
551               unsigned char *add, size_t addlen)
552 {
553   /* implied: dstlen > addlen */
554   unsigned char *dstptr, *addptr;
555   unsigned int remainder = 0;
556   size_t len = addlen;
557 
558   dstptr = dst + (dstlen - 1);
559   addptr = add + (addlen - 1);
560   while (len)
561     {
562       remainder += *dstptr + *addptr;
563       *dstptr = remainder & 0xff;
564       remainder >>= 8;
565       len--;
566       dstptr--;
567       addptr--;
568     }
569   len = dstlen - addlen;
570   while (len && remainder > 0)
571     {
572       remainder = *dstptr + 1;
573       *dstptr = remainder & 0xff;
574       remainder >>= 8;
575       len--;
576       dstptr--;
577     }
578 }
579 
580 /* Helper variables for read_cb().
581  *
582  *   The _gcry_rnd*_gather_random interface does not allow to provide a
583  *   data pointer.  Thus we need to use a global variable for
584  *   communication.  However, the then required locking is anyway a good
585  *   idea because it does not make sense to have several readers of (say
586  *   /dev/random).  It is easier to serve them one after the other.
587  */
588 static unsigned char *read_cb_buffer;	/* The buffer.  */
589 static size_t read_cb_size;	        /* Size of the buffer.  */
590 static size_t read_cb_len;	        /* Used length.  */
591 
592 /* Callback for generating seed from kernel device. */
593 static void
drbg_read_cb(const void * buffer,size_t length,enum random_origins origin)594 drbg_read_cb (const void *buffer, size_t length,
595               enum random_origins origin)
596 {
597   const unsigned char *p = buffer;
598 
599   (void) origin;
600   gcry_assert (read_cb_buffer);
601 
602   /* Note that we need to protect against gatherers returning more
603    * than the requested bytes (e.g. rndw32).  */
604   while (length-- && read_cb_len < read_cb_size)
605     read_cb_buffer[read_cb_len++] = *p++;
606 }
607 
608 static inline int
drbg_get_entropy(drbg_state_t drbg,unsigned char * buffer,size_t len)609 drbg_get_entropy (drbg_state_t drbg, unsigned char *buffer,
610 		       size_t len)
611 {
612   int rc = 0;
613 
614   /* Perform testing as defined in 11.3.2 */
615   if (drbg->test_data && drbg->test_data->fail_seed_source)
616     return -1;
617 
618   read_cb_buffer = buffer;
619   read_cb_size = len;
620   read_cb_len = 0;
621 #if USE_RNDLINUX
622   rc = _gcry_rndlinux_gather_random (drbg_read_cb, 0, len,
623 				     GCRY_VERY_STRONG_RANDOM);
624 #elif USE_RNDUNIX
625   rc = _gcry_rndunix_gather_random (drbg_read_cb, 0, len,
626 				    GCRY_VERY_STRONG_RANDOM);
627 #elif USE_RNDW32
628   do
629     {
630       rc = _gcry_rndw32_gather_random (drbg_read_cb, 0, len,
631 				       GCRY_VERY_STRONG_RANDOM);
632     }
633   while (rc >= 0 && read_cb_len < read_cb_size);
634 #else
635   rc = -1;
636 #endif
637   return rc;
638 }
639 
640 /******************************************************************
641  * CTR DRBG callback functions
642  ******************************************************************/
643 
644 /* BCC function for CTR DRBG as defined in 10.4.3 */
645 static gpg_err_code_t
drbg_ctr_bcc(drbg_state_t drbg,unsigned char * out,const unsigned char * key,drbg_string_t * in)646 drbg_ctr_bcc (drbg_state_t drbg,
647               unsigned char *out, const unsigned char *key,
648               drbg_string_t *in)
649 {
650   gpg_err_code_t ret = GPG_ERR_GENERAL;
651   drbg_string_t *curr = in;
652   size_t inpos = curr->len;
653   const unsigned char *pos = curr->buf;
654   drbg_string_t data;
655 
656   drbg_string_fill (&data, out, drbg_blocklen (drbg));
657 
658   /* 10.4.3 step 1 */
659   memset (out, 0, drbg_blocklen (drbg));
660 
661   ret = drbg_sym_setkey(drbg, key);
662   if (ret)
663     return ret;
664 
665   /* 10.4.3 step 2 / 4 */
666   while (inpos)
667     {
668       short cnt = 0;
669       /* 10.4.3 step 4.1 */
670       for (cnt = 0; cnt < drbg_blocklen (drbg); cnt++)
671 	{
672 	  out[cnt] ^= *pos;
673 	  pos++;
674 	  inpos--;
675 	  /* the following branch implements the linked list
676 	   * iteration. If we are at the end of the current data
677 	   * set, we have to start using the next data set if
678 	   * available -- the inpos value always points to the
679 	   * current byte and will be zero if we have processed
680 	   * the last byte of the last linked list member */
681 	  if (0 == inpos)
682 	    {
683 	      curr = curr->next;
684 	      if (NULL != curr)
685 		{
686 		  pos = curr->buf;
687 		  inpos = curr->len;
688 		}
689 	      else
690 		{
691 		  inpos = 0;
692 		  break;
693 		}
694 	    }
695 	}
696       /* 10.4.3 step 4.2 */
697       ret = drbg_sym (drbg, out, &data);
698       if (ret)
699 	return ret;
700       /* 10.4.3 step 2 */
701     }
702   return 0;
703 }
704 
705 
706 /*
707  * scratchpad usage: drbg_ctr_update is interlinked with drbg_ctr_df
708  * (and drbg_ctr_bcc, but this function does not need any temporary buffers),
709  * the scratchpad is used as follows:
710  * drbg_ctr_update:
711  *	temp
712  *		start: drbg->scratchpad
713  *		length: drbg_statelen(drbg) + drbg_blocklen(drbg)
714  *			note: the cipher writing into this variable works
715  *			blocklen-wise. Now, when the statelen is not a multiple
716  *			of blocklen, the generateion loop below "spills over"
717  *			by at most blocklen. Thus, we need to give sufficient
718  *			memory.
719  *	df_data
720  *		start: drbg->scratchpad +
721  *				drbg_statelen(drbg) +
722  *				drbg_blocklen(drbg)
723  *		length: drbg_statelen(drbg)
724  *
725  * drbg_ctr_df:
726  *	pad
727  *		start: df_data + drbg_statelen(drbg)
728  *		length: drbg_blocklen(drbg)
729  *	iv
730  *		start: pad + drbg_blocklen(drbg)
731  *		length: drbg_blocklen(drbg)
732  *	temp
733  *		start: iv + drbg_blocklen(drbg)
734  *		length: drbg_satelen(drbg) + drbg_blocklen(drbg)
735  *			note: temp is the buffer that the BCC function operates
736  *			on. BCC operates blockwise. drbg_statelen(drbg)
737  *			is sufficient when the DRBG state length is a multiple
738  *			of the block size. For AES192 (and maybe other ciphers)
739  *			this is not correct and the length for temp is
740  *			insufficient (yes, that also means for such ciphers,
741  *			the final output of all BCC rounds are truncated).
742  *			Therefore, add drbg_blocklen(drbg) to cover all
743  *			possibilities.
744  */
745 
746 /* Derivation Function for CTR DRBG as defined in 10.4.2 */
747 static gpg_err_code_t
drbg_ctr_df(drbg_state_t drbg,unsigned char * df_data,size_t bytes_to_return,drbg_string_t * addtl)748 drbg_ctr_df (drbg_state_t drbg, unsigned char *df_data,
749              size_t bytes_to_return, drbg_string_t *addtl)
750 {
751   gpg_err_code_t ret = GPG_ERR_GENERAL;
752   unsigned char L_N[8];
753   /* S3 is input */
754   drbg_string_t S1, S2, S4, cipherin;
755   drbg_string_t *tempstr = addtl;
756   unsigned char *pad = df_data + drbg_statelen (drbg);
757   unsigned char *iv = pad + drbg_blocklen (drbg);
758   unsigned char *temp = iv + drbg_blocklen (drbg);
759   size_t padlen = 0;
760   unsigned int templen = 0;
761   /* 10.4.2 step 7 */
762   unsigned int i = 0;
763   /* 10.4.2 step 8 */
764   const unsigned char *K = (unsigned char *)
765     "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
766     "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f";
767   unsigned char *X;
768   size_t generated_len = 0;
769   size_t inputlen = 0;
770 
771   memset (pad, 0, drbg_blocklen (drbg));
772   memset (iv, 0, drbg_blocklen (drbg));
773   memset (temp, 0, drbg_statelen (drbg));
774 
775   /* 10.4.2 step 1 is implicit as we work byte-wise */
776 
777   /* 10.4.2 step 2 */
778   if ((512 / 8) < bytes_to_return)
779     return GPG_ERR_INV_ARG;
780 
781   /* 10.4.2 step 2 -- calculate the entire length of all input data */
782   for (; NULL != tempstr; tempstr = tempstr->next)
783     inputlen += tempstr->len;
784   buf_put_be32 (&L_N[0], inputlen);
785 
786   /* 10.4.2 step 3 */
787   buf_put_be32 (&L_N[4], bytes_to_return);
788 
789   /* 10.4.2 step 5: length is size of L_N, input_string, one byte, padding */
790   padlen = (inputlen + sizeof (L_N) + 1) % (drbg_blocklen (drbg));
791   /* wrap the padlen appropriately */
792   if (padlen)
793     padlen = drbg_blocklen (drbg) - padlen;
794   /* pad / padlen contains the 0x80 byte and the following zero bytes, so
795    * add one for byte for 0x80 */
796   padlen++;
797   pad[0] = 0x80;
798 
799   /* 10.4.2 step 4 -- first fill the linked list and then order it */
800   drbg_string_fill (&S1, iv, drbg_blocklen (drbg));
801   drbg_string_fill (&S2, L_N, sizeof (L_N));
802   drbg_string_fill (&S4, pad, padlen);
803   S1.next = &S2;
804   S2.next = addtl;
805 
806   /* Splice in addtl between S2 and S4 -- we place S4 at the end of the
807    * input data chain. As this code is only triggered when addtl is not
808    * NULL, no NULL checks are necessary.*/
809   tempstr = addtl;
810   while (tempstr->next)
811     tempstr = tempstr->next;
812   tempstr->next = &S4;
813 
814   /* 10.4.2 step 9 */
815   while (templen < (drbg_keylen (drbg) + (drbg_blocklen (drbg))))
816     {
817       /* 10.4.2 step 9.1 - the padding is implicit as the buffer
818        * holds zeros after allocation -- even the increment of i
819        * is irrelevant as the increment remains within length of i */
820       buf_put_be32 (iv, i);
821       /* 10.4.2 step 9.2 -- BCC and concatenation with temp */
822       ret = drbg_ctr_bcc (drbg, temp + templen, K, &S1);
823       if (ret)
824 	goto out;
825       /* 10.4.2 step 9.3 */
826       i++;
827       templen += drbg_blocklen (drbg);
828     }
829 
830   /* 10.4.2 step 11 */
831   /* implicit key len with seedlen - blocklen according to table 3 */
832   X = temp + (drbg_keylen (drbg));
833   drbg_string_fill (&cipherin, X, drbg_blocklen (drbg));
834 
835   /* 10.4.2 step 12: overwriting of outval */
836 
837   /* 10.4.2 step 13 */
838   ret = drbg_sym_setkey(drbg, temp);
839   if (ret)
840     goto out;
841   while (generated_len < bytes_to_return)
842     {
843       short blocklen = 0;
844       /* 10.4.2 step 13.1 */
845       /* the truncation of the key length is implicit as the key
846        * is only drbg_blocklen in size -- check for the implementation
847        * of the cipher function callback */
848       ret = drbg_sym (drbg, X, &cipherin);
849       if (ret)
850 	goto out;
851       blocklen = (drbg_blocklen (drbg) < (bytes_to_return - generated_len)) ?
852 	drbg_blocklen (drbg) : (bytes_to_return - generated_len);
853       /* 10.4.2 step 13.2 and 14 */
854       memcpy (df_data + generated_len, X, blocklen);
855       generated_len += blocklen;
856     }
857 
858   ret = 0;
859 
860  out:
861   memset (iv, 0, drbg_blocklen (drbg));
862   memset (temp, 0, drbg_statelen (drbg));
863   memset (pad, 0, drbg_blocklen (drbg));
864   return ret;
865 }
866 
867 /*
868  * Update function of CTR DRBG as defined in 10.2.1.2
869  *
870  * The reseed variable has an enhanced meaning compared to the update
871  * functions of the other DRBGs as follows:
872  * 0 => initial seed from initialization
873  * 1 => reseed via drbg_seed
874  * 2 => first invocation from drbg_ctr_update when addtl is present. In
875  *      this case, the df_data scratchpad is not deleted so that it is
876  *      available for another calls to prevent calling the DF function
877  *      again.
878  * 3 => second invocation from drbg_ctr_update. When the update function
879  *      was called with addtl, the df_data memory already contains the
880  *      DFed addtl information and we do not need to call DF again.
881  */
882 static gpg_err_code_t
drbg_ctr_update(drbg_state_t drbg,drbg_string_t * addtl,int reseed)883 drbg_ctr_update (drbg_state_t drbg, drbg_string_t *addtl, int reseed)
884 {
885   gpg_err_code_t ret = GPG_ERR_GENERAL;
886   /* 10.2.1.2 step 1 */
887   unsigned char *temp = drbg->scratchpad;
888   unsigned char *df_data = drbg->scratchpad +
889     drbg_statelen (drbg) + drbg_blocklen (drbg);
890   unsigned char prefix = DRBG_PREFIX1;
891 
892   memset (temp, 0, drbg_statelen (drbg) + drbg_blocklen (drbg));
893   if (3 > reseed)
894     memset (df_data, 0, drbg_statelen (drbg));
895 
896   if (!reseed)
897     {
898       /*
899        * The DRBG uses the CTR mode of the underlying AES cipher. The
900        * CTR mode increments the counter value after the AES operation
901        * but SP800-90A requires that the counter is incremented before
902        * the AES operation. Hence, we increment it at the time we set
903        * it by one.
904        */
905       drbg_add_buf (drbg->V, drbg_blocklen (drbg), &prefix, 1);
906 
907       ret = _gcry_cipher_setkey (drbg->ctr_handle, drbg->C, drbg_keylen (drbg));
908       if (ret)
909         goto out;
910     }
911 
912   /* 10.2.1.3.2 step 2 and 10.2.1.4.2 step 2 */
913   if (addtl && 0 < addtl->len)
914     {
915       ret =
916 	drbg_ctr_df (drbg, df_data, drbg_statelen (drbg), addtl);
917       if (ret)
918 	goto out;
919     }
920 
921   ret = drbg_sym_ctr (drbg, df_data, drbg_statelen(drbg),
922 		      temp, drbg_statelen(drbg));
923   if (ret)
924     goto out;
925 
926   /* 10.2.1.2 step 5 */
927   ret = _gcry_cipher_setkey (drbg->ctr_handle, temp, drbg_keylen (drbg));
928   if (ret)
929     goto out;
930 
931   /* 10.2.1.2 step 6 */
932   memcpy (drbg->V, temp + drbg_keylen (drbg), drbg_blocklen (drbg));
933   /* See above: increment counter by one to compensate timing of CTR op */
934   drbg_add_buf (drbg->V, drbg_blocklen (drbg), &prefix, 1);
935   ret = 0;
936 
937  out:
938   memset (temp, 0, drbg_statelen (drbg) + drbg_blocklen (drbg));
939   if (2 != reseed)
940     memset (df_data, 0, drbg_statelen (drbg));
941   return ret;
942 }
943 
944 /*
945  * scratchpad use: drbg_ctr_update is called independently from
946  * drbg_ctr_extract_bytes. Therefore, the scratchpad is reused
947  */
948 /* Generate function of CTR DRBG as defined in 10.2.1.5.2 */
949 static gpg_err_code_t
drbg_ctr_generate(drbg_state_t drbg,unsigned char * buf,unsigned int buflen,drbg_string_t * addtl)950 drbg_ctr_generate (drbg_state_t drbg,
951                    unsigned char *buf, unsigned int buflen,
952                    drbg_string_t *addtl)
953 {
954   static const unsigned char drbg_ctr_null[DRBG_CTR_NULL_LEN] = { 0, };
955   gpg_err_code_t ret = 0;
956 
957   memset (drbg->scratchpad, 0, drbg_blocklen (drbg));
958 
959   /* 10.2.1.5.2 step 2 */
960   if (addtl && 0 < addtl->len)
961     {
962       addtl->next = NULL;
963       ret = drbg_ctr_update (drbg, addtl, 2);
964       if (ret)
965 	return ret;
966     }
967 
968   /* 10.2.1.5.2 step 4.1 */
969   ret = drbg_sym_ctr (drbg, drbg_ctr_null, sizeof(drbg_ctr_null), buf, buflen);
970   if (ret)
971     goto out;
972 
973   /* 10.2.1.5.2 step 6 */
974   if (addtl)
975     addtl->next = NULL;
976   ret = drbg_ctr_update (drbg, addtl, 3);
977 
978  out:
979   return ret;
980 }
981 
982 static struct drbg_state_ops_s drbg_ctr_ops = {
983   drbg_ctr_update,
984   drbg_ctr_generate,
985   drbg_sym_init,
986   drbg_sym_fini,
987 };
988 
989 /******************************************************************
990  * HMAC DRBG callback functions
991  ******************************************************************/
992 
993 static gpg_err_code_t
drbg_hmac_update(drbg_state_t drbg,drbg_string_t * seed,int reseed)994 drbg_hmac_update (drbg_state_t drbg, drbg_string_t *seed, int reseed)
995 {
996   gpg_err_code_t ret = GPG_ERR_GENERAL;
997   int i = 0;
998   drbg_string_t seed1, seed2, cipherin;
999 
1000   if (!reseed)
1001     {
1002       /* 10.1.2.3 step 2 already implicitly covered with
1003        * the initial memset(0) of drbg->C */
1004       memset (drbg->V, 1, drbg_statelen (drbg));
1005       ret = drbg_hmac_setkey (drbg, drbg->C);
1006       if (ret)
1007 	return ret;
1008     }
1009 
1010   /* build linked list which implements the concatenation and fill
1011    * first part*/
1012   drbg_string_fill (&seed1, drbg->V, drbg_statelen (drbg));
1013   /* buffer will be filled in for loop below with one byte */
1014   drbg_string_fill (&seed2, NULL, 1);
1015   seed1.next = &seed2;
1016   /* seed may be NULL */
1017   seed2.next = seed;
1018 
1019   drbg_string_fill (&cipherin, drbg->V, drbg_statelen (drbg));
1020   /* we execute two rounds of V/K massaging */
1021   for (i = 2; 0 < i; i--)
1022     {
1023       byte *retval;
1024       /* first round uses 0x0, second 0x1 */
1025       unsigned char prefix = DRBG_PREFIX0;
1026       if (1 == i)
1027 	prefix = DRBG_PREFIX1;
1028       /* 10.1.2.2 step 1 and 4 -- concatenation and HMAC for key */
1029       seed2.buf = &prefix;
1030       retval = drbg_hash (drbg, &seed1);
1031       ret = drbg_hmac_setkey (drbg, retval);
1032       if (ret)
1033 	return ret;
1034 
1035       /* 10.1.2.2 step 2 and 5 -- HMAC for V */
1036       retval = drbg_hash (drbg, &cipherin);
1037       memcpy(drbg->V, retval, drbg_blocklen (drbg));
1038 
1039       /* 10.1.2.2 step 3 */
1040       if (!seed || 0 == seed->len)
1041 	return ret;
1042     }
1043   return 0;
1044 }
1045 
1046 /* generate function of HMAC DRBG as defined in 10.1.2.5 */
1047 static gpg_err_code_t
drbg_hmac_generate(drbg_state_t drbg,unsigned char * buf,unsigned int buflen,drbg_string_t * addtl)1048 drbg_hmac_generate (drbg_state_t drbg, unsigned char *buf, unsigned int buflen,
1049                     drbg_string_t *addtl)
1050 {
1051   gpg_err_code_t ret = 0;
1052   unsigned int len = 0;
1053   drbg_string_t data;
1054 
1055   /* 10.1.2.5 step 2 */
1056   if (addtl && 0 < addtl->len)
1057     {
1058       addtl->next = NULL;
1059       ret = drbg_hmac_update (drbg, addtl, 1);
1060       if (ret)
1061 	return ret;
1062     }
1063 
1064   drbg_string_fill (&data, drbg->V, drbg_statelen (drbg));
1065   while (len < buflen)
1066     {
1067       unsigned int outlen = 0;
1068       /* 10.1.2.5 step 4.1 */
1069       byte *retval = drbg_hash (drbg, &data);
1070       memcpy(drbg->V, retval, drbg_blocklen (drbg));
1071       outlen = (drbg_blocklen (drbg) < (buflen - len)) ?
1072 	drbg_blocklen (drbg) : (buflen - len);
1073 
1074       /* 10.1.2.5 step 4.2 */
1075       memcpy (buf + len, drbg->V, outlen);
1076       len += outlen;
1077     }
1078 
1079   /* 10.1.2.5 step 6 */
1080   if (addtl)
1081     addtl->next = NULL;
1082   ret = drbg_hmac_update (drbg, addtl, 1);
1083 
1084   return ret;
1085 }
1086 
1087 static struct drbg_state_ops_s drbg_hmac_ops = {
1088   drbg_hmac_update,
1089   drbg_hmac_generate,
1090   drbg_hmac_init,
1091   drbg_hash_fini,
1092 };
1093 
1094 /******************************************************************
1095  * Hash DRBG callback functions
1096  ******************************************************************/
1097 
1098 /*
1099  * scratchpad usage: as drbg_hash_update and drbg_hash_df are used
1100  * interlinked, the scratchpad is used as follows:
1101  * drbg_hash_update
1102  *	start: drbg->scratchpad
1103  *	length: drbg_statelen(drbg)
1104  * drbg_hash_df:
1105  *	start: drbg->scratchpad + drbg_statelen(drbg)
1106  *	length: drbg_blocklen(drbg)
1107  */
1108 /* Derivation Function for Hash DRBG as defined in 10.4.1 */
1109 static gpg_err_code_t
drbg_hash_df(drbg_state_t drbg,unsigned char * outval,size_t outlen,drbg_string_t * entropy)1110 drbg_hash_df (drbg_state_t drbg,
1111               unsigned char *outval, size_t outlen,
1112               drbg_string_t *entropy)
1113 {
1114   size_t len = 0;
1115   unsigned char input[5];
1116   drbg_string_t data1;
1117 
1118   /* 10.4.1 step 3 */
1119   input[0] = 1;
1120   buf_put_be32 (&input[1], (outlen * 8));
1121 
1122   /* 10.4.1 step 4.1 -- concatenation of data for input into hash */
1123   drbg_string_fill (&data1, input, 5);
1124   data1.next = entropy;
1125 
1126   /* 10.4.1 step 4 */
1127   while (len < outlen)
1128     {
1129       short blocklen = 0;
1130       /* 10.4.1 step 4.1 */
1131       byte *retval = drbg_hash (drbg, &data1);
1132       /* 10.4.1 step 4.2 */
1133       input[0]++;
1134       blocklen = (drbg_blocklen (drbg) < (outlen - len)) ?
1135 	drbg_blocklen (drbg) : (outlen - len);
1136       memcpy (outval + len, retval, blocklen);
1137       len += blocklen;
1138     }
1139 
1140   return 0;
1141 }
1142 
1143 /* update function for Hash DRBG as defined in 10.1.1.2 / 10.1.1.3 */
1144 static gpg_err_code_t
drbg_hash_update(drbg_state_t drbg,drbg_string_t * seed,int reseed)1145 drbg_hash_update (drbg_state_t drbg, drbg_string_t *seed, int reseed)
1146 {
1147   gpg_err_code_t ret = 0;
1148   drbg_string_t data1, data2;
1149   unsigned char *V = drbg->scratchpad;
1150   unsigned char prefix = DRBG_PREFIX1;
1151 
1152   memset (drbg->scratchpad, 0, drbg_statelen (drbg));
1153   if (!seed)
1154     return GPG_ERR_INV_ARG;
1155 
1156   if (reseed)
1157     {
1158       /* 10.1.1.3 step 1: string length is concatenation of
1159        * 1 byte, V and seed (which is concatenated entropy/addtl
1160        * input)
1161        */
1162       memcpy (V, drbg->V, drbg_statelen (drbg));
1163       drbg_string_fill (&data1, &prefix, 1);
1164       drbg_string_fill (&data2, V, drbg_statelen (drbg));
1165       data1.next = &data2;
1166       data2.next = seed;
1167     }
1168   else
1169     {
1170       drbg_string_fill (&data1, seed->buf, seed->len);
1171       data1.next = seed->next;
1172     }
1173 
1174   /* 10.1.1.2 / 10.1.1.3 step 2 and 3 */
1175   ret = drbg_hash_df (drbg, drbg->V, drbg_statelen (drbg), &data1);
1176   if (ret)
1177     goto out;
1178 
1179   /* 10.1.1.2 / 10.1.1.3 step 4 -- concatenation  */
1180   prefix = DRBG_PREFIX0;
1181   drbg_string_fill (&data1, &prefix, 1);
1182   drbg_string_fill (&data2, drbg->V, drbg_statelen (drbg));
1183   data1.next = &data2;
1184   /* 10.1.1.2 / 10.1.1.3 step 4 -- df operation */
1185   ret = drbg_hash_df (drbg, drbg->C, drbg_statelen (drbg), &data1);
1186 
1187  out:
1188   memset (drbg->scratchpad, 0, drbg_statelen (drbg));
1189   return ret;
1190 }
1191 
1192 /* Processing of additional information string for Hash DRBG.  */
1193 static gpg_err_code_t
drbg_hash_process_addtl(drbg_state_t drbg,drbg_string_t * addtl)1194 drbg_hash_process_addtl (drbg_state_t drbg, drbg_string_t *addtl)
1195 {
1196   drbg_string_t data1, data2;
1197   drbg_string_t *data3;
1198   unsigned char prefix = DRBG_PREFIX2;
1199   byte *retval;
1200 
1201   /* 10.1.1.4 step 2 */
1202   if (!addtl || 0 == addtl->len)
1203     return 0;
1204 
1205   /* 10.1.1.4 step 2a -- concatenation */
1206   drbg_string_fill (&data1, &prefix, 1);
1207   drbg_string_fill (&data2, drbg->V, drbg_statelen (drbg));
1208   data3 = addtl;
1209   data1.next = &data2;
1210   data2.next = data3;
1211   data3->next = NULL;
1212   /* 10.1.1.4 step 2a -- cipher invocation */
1213   retval = drbg_hash (drbg, &data1);
1214 
1215   /* 10.1.1.4 step 2b */
1216   drbg_add_buf (drbg->V, drbg_statelen (drbg), retval, drbg_blocklen (drbg));
1217 
1218   return 0;
1219 }
1220 
1221 /*
1222  * Hashgen defined in 10.1.1.4
1223  */
1224 static gpg_err_code_t
drbg_hash_hashgen(drbg_state_t drbg,unsigned char * buf,unsigned int buflen)1225 drbg_hash_hashgen (drbg_state_t drbg, unsigned char *buf, unsigned int buflen)
1226 {
1227   unsigned int len = 0;
1228   unsigned char *src = drbg->scratchpad;
1229   drbg_string_t data;
1230   unsigned char prefix = DRBG_PREFIX1;
1231 
1232   /* 10.1.1.4 step hashgen 2 */
1233   memcpy (src, drbg->V, drbg_statelen (drbg));
1234 
1235   drbg_string_fill (&data, src, drbg_statelen (drbg));
1236   while (len < buflen)
1237     {
1238       unsigned int outlen = 0;
1239       /* 10.1.1.4 step hashgen 4.1 */
1240       byte *retval = drbg_hash (drbg, &data);
1241       outlen = (drbg_blocklen (drbg) < (buflen - len)) ?
1242 	drbg_blocklen (drbg) : (buflen - len);
1243       /* 10.1.1.4 step hashgen 4.2 */
1244       memcpy (buf + len, retval, outlen);
1245       len += outlen;
1246       /* 10.1.1.4 hashgen step 4.3 */
1247       if (len < buflen)
1248 	drbg_add_buf (src, drbg_statelen (drbg), &prefix, 1);
1249     }
1250 
1251   memset (drbg->scratchpad, 0, drbg_statelen (drbg));
1252   return 0;
1253 }
1254 
1255 /* Generate function for Hash DRBG as defined in 10.1.1.4  */
1256 static gpg_err_code_t
drbg_hash_generate(drbg_state_t drbg,unsigned char * buf,unsigned int buflen,drbg_string_t * addtl)1257 drbg_hash_generate (drbg_state_t drbg, unsigned char *buf, unsigned int buflen,
1258 		    drbg_string_t *addtl)
1259 {
1260   gpg_err_code_t ret;
1261   unsigned char prefix = DRBG_PREFIX3;
1262   drbg_string_t data1, data2;
1263   byte *retval;
1264   union
1265   {
1266     unsigned char req[8];
1267     u64 req_int;
1268   } u;
1269 
1270   /* 10.1.1.4 step 2 */
1271   ret = drbg_hash_process_addtl (drbg, addtl);
1272   if (ret)
1273     return ret;
1274   /* 10.1.1.4 step 3 -- invocation of the Hashgen function defined in
1275    * 10.1.1.4 */
1276   ret = drbg_hash_hashgen (drbg, buf, buflen);
1277   if (ret)
1278     return ret;
1279 
1280   /* 10.1.1.4 step 4 */
1281   drbg_string_fill (&data1, &prefix, 1);
1282   drbg_string_fill (&data2, drbg->V, drbg_statelen (drbg));
1283   data1.next = &data2;
1284 
1285   /* this is the value H as documented in 10.1.1.4 */
1286   retval = drbg_hash (drbg, &data1);
1287 
1288   /* 10.1.1.4 step 5 */
1289   drbg_add_buf (drbg->V, drbg_statelen (drbg), retval, drbg_blocklen (drbg));
1290   drbg_add_buf (drbg->V, drbg_statelen (drbg), drbg->C, drbg_statelen (drbg));
1291   u.req_int = be_bswap64 (drbg->reseed_ctr);
1292   drbg_add_buf (drbg->V, drbg_statelen (drbg), u.req, sizeof (u.req));
1293 
1294   return ret;
1295 }
1296 
1297 /*
1298  * scratchpad usage: as update and generate are used isolated, both
1299  * can use the scratchpad
1300  */
1301 static struct drbg_state_ops_s drbg_hash_ops = {
1302   drbg_hash_update,
1303   drbg_hash_generate,
1304   drbg_hash_init,
1305   drbg_hash_fini,
1306 };
1307 
1308 /******************************************************************
1309  * Functions common for DRBG implementations
1310  ******************************************************************/
1311 
1312 /*
1313  * Seeding or reseeding of the DRBG
1314  *
1315  * @drbg: DRBG state struct
1316  * @pers: personalization / additional information buffer
1317  * @reseed: 0 for initial seed process, 1 for reseeding
1318  *
1319  * return:
1320  *	0 on success
1321  *	error value otherwise
1322  */
1323 static gpg_err_code_t
drbg_seed(drbg_state_t drbg,drbg_string_t * pers,int reseed)1324 drbg_seed (drbg_state_t drbg, drbg_string_t *pers, int reseed)
1325 {
1326   gpg_err_code_t ret = 0;
1327   unsigned char *entropy = NULL;
1328   size_t entropylen = 0;
1329   drbg_string_t data1;
1330 
1331   /* 9.1 / 9.2 / 9.3.1 step 3 */
1332   if (pers && pers->len > (drbg_max_addtl ()))
1333     {
1334       dbg (("DRBG: personalization string too long %lu\n", pers->len));
1335       return GPG_ERR_INV_ARG;
1336     }
1337   if (drbg->test_data && drbg->test_data->testentropy)
1338     {
1339       drbg_string_fill (&data1, drbg->test_data->testentropy->buf,
1340 			     drbg->test_data->testentropy->len);
1341       dbg (("DRBG: using test entropy\n"));
1342     }
1343   else
1344     {
1345       /* Gather entropy equal to the security strength of the DRBG.
1346        * With a derivation function, a nonce is required in addition
1347        * to the entropy. A nonce must be at least 1/2 of the security
1348        * strength of the DRBG in size. Thus, entropy * nonce is 3/2
1349        * of the strength. The consideration of a nonce is only
1350        * applicable during initial seeding. */
1351       entropylen = drbg_sec_strength (drbg->core->flags);
1352       if (!entropylen)
1353 	return GPG_ERR_GENERAL;
1354       if (0 == reseed)
1355 	/* make sure we round up strength/2 in
1356 	 * case it is not divisible by 2 */
1357 	entropylen = ((entropylen + 1) / 2) * 3;
1358       dbg (("DRBG: (re)seeding with %lu bytes of entropy\n", entropylen));
1359       entropy = xcalloc_secure (1, entropylen);
1360       if (!entropy)
1361 	return GPG_ERR_ENOMEM;
1362       ret = drbg_get_entropy (drbg, entropy, entropylen);
1363       if (ret)
1364 	goto out;
1365       drbg_string_fill (&data1, entropy, entropylen);
1366     }
1367 
1368   /* concatenation of entropy with personalization str / addtl input)
1369    * the variable pers is directly handed by the caller, check its
1370    * contents whether it is appropriate */
1371   if (pers && pers->buf && 0 < pers->len && NULL == pers->next)
1372     {
1373       data1.next = pers;
1374       dbg (("DRBG: using personalization string\n"));
1375     }
1376 
1377   ret = drbg->d_ops->update (drbg, &data1, reseed);
1378   dbg (("DRBG: state updated with seed\n"));
1379   if (ret)
1380     goto out;
1381   drbg->seeded = 1;
1382   /* 10.1.1.2 / 10.1.1.3 step 5 */
1383   drbg->reseed_ctr = 1;
1384 
1385  out:
1386   xfree (entropy);
1387   return ret;
1388 }
1389 
1390 
1391 /*************************************************************************
1392  * Exported interfaces.
1393  *************************************************************************/
1394 
1395 /*
1396  * DRBG generate function as required by SP800-90A - this function
1397  * generates random numbers
1398  *
1399  * @drbg   DRBG state handle
1400  * @buf    Buffer where to store the random numbers -- the buffer must already
1401  *         be pre-allocated by caller
1402  * @buflen Length of output buffer - this value defines the number of random
1403  *	   bytes pulled from DRBG
1404  * @addtl  Additional input that is mixed into state, may be NULL -- note
1405  *	   the entropy is pulled by the DRBG internally unconditionally
1406  *	   as defined in SP800-90A. The additional input is mixed into
1407  *	   the state in addition to the pulled entropy.
1408  *
1409  * return: Generated number of bytes.
1410  */
1411 static gpg_err_code_t
drbg_generate(drbg_state_t drbg,unsigned char * buf,unsigned int buflen,drbg_string_t * addtl)1412 drbg_generate (drbg_state_t drbg,
1413                unsigned char *buf, unsigned int buflen,
1414                drbg_string_t *addtl)
1415 {
1416   gpg_err_code_t ret = GPG_ERR_INV_ARG;
1417 
1418   if (0 == buflen || !buf)
1419     {
1420       dbg (("DRBG: no buffer provided\n"));
1421       return ret;
1422     }
1423   if (addtl && NULL == addtl->buf && 0 < addtl->len)
1424     {
1425       dbg (("DRBG: wrong format of additional information\n"));
1426       return ret;
1427     }
1428 
1429   /* 9.3.1 step 2 */
1430   if (buflen > (drbg_max_request_bytes ()))
1431     {
1432       dbg (("DRBG: requested random numbers too large %u\n", buflen));
1433       return ret;
1434     }
1435   /* 9.3.1 step 3 is implicit with the chosen DRBG */
1436   /* 9.3.1 step 4 */
1437   if (addtl && addtl->len > (drbg_max_addtl ()))
1438     {
1439       dbg (("DRBG: additional information string too long %lu\n",
1440 	    addtl->len));
1441       return ret;
1442     }
1443   /* 9.3.1 step 5 is implicit with the chosen DRBG */
1444   /* 9.3.1 step 6 and 9 supplemented by 9.3.2 step c -- the spec is a
1445    * bit convoluted here, we make it simpler */
1446   if ((drbg_max_requests ()) < drbg->reseed_ctr)
1447     drbg->seeded = 0;
1448 
1449   if (drbg->pr || !drbg->seeded)
1450     {
1451       dbg (("DRBG: reseeding before generation (prediction resistance: %s, state %s)\n", drbg->pr ? "true" : "false", drbg->seeded ? "seeded" : "unseeded"));
1452       /* 9.3.1 steps 7.1 through 7.3 */
1453       ret = drbg_seed (drbg, addtl, 1);
1454       if (ret)
1455 	return ret;
1456       /* 9.3.1 step 7.4 */
1457       addtl = NULL;
1458     }
1459 
1460   if (addtl && addtl->buf)
1461     {
1462       dbg (("DRBG: using additional information string\n"));
1463     }
1464 
1465   /* 9.3.1 step 8 and 10 */
1466   ret = drbg->d_ops->generate (drbg, buf, buflen, addtl);
1467 
1468   /* 10.1.1.4 step 6, 10.1.2.5 step 7, 10.2.1.5.2 step 7 */
1469   drbg->reseed_ctr++;
1470   if (ret)
1471     return ret;
1472 
1473   /* 11.3.3 -- re-perform self tests after some generated random
1474    * numbers, the chosen value after which self test is performed
1475    * is arbitrary, but it should be reasonable */
1476   /* Here we do not perform the self tests because of the following
1477    * reasons: it is mathematically impossible that the initial self tests
1478    * were successfully and the following are not. If the initial would
1479    * pass and the following would not, the system integrity is violated.
1480    * In this case, the entire system operation is questionable and it
1481    * is unlikely that the integrity violation only affects to the
1482    * correct operation of the DRBG.
1483    */
1484 #if 0
1485   if (drbg->reseed_ctr && !(drbg->reseed_ctr % 4096))
1486     {
1487       dbg (("DRBG: start to perform self test\n"));
1488       ret = drbg_healthcheck ();
1489       if (ret)
1490 	{
1491 	  log_fatal (("DRBG: self test failed\n"));
1492 	  return ret;
1493 	}
1494       else
1495 	{
1496 	  dbg (("DRBG: self test successful\n"));
1497 	}
1498     }
1499 #endif
1500 
1501   return ret;
1502 }
1503 
1504 /*
1505  * Wrapper around drbg_generate which can pull arbitrary long strings
1506  * from the DRBG without hitting the maximum request limitation.
1507  *
1508  * Parameters: see drbg_generate
1509  * Return codes: see drbg_generate -- if one drbg_generate request fails,
1510  *		 the entire drbg_generate_long request fails
1511  */
1512 static gpg_err_code_t
drbg_generate_long(drbg_state_t drbg,unsigned char * buf,unsigned int buflen,drbg_string_t * addtl)1513 drbg_generate_long (drbg_state_t drbg,
1514                     unsigned char *buf, unsigned int buflen,
1515                     drbg_string_t *addtl)
1516 {
1517   gpg_err_code_t ret = 0;
1518   unsigned int slice = 0;
1519   unsigned char *buf_p = buf;
1520   unsigned len = 0;
1521   do
1522     {
1523       unsigned int chunk = 0;
1524       slice = ((buflen - len) / drbg_max_request_bytes ());
1525       chunk = slice ? drbg_max_request_bytes () : (buflen - len);
1526       ret = drbg_generate (drbg, buf_p, chunk, addtl);
1527       if (ret)
1528 	return ret;
1529       buf_p += chunk;
1530       len += chunk;
1531     }
1532   while (slice > 0 && (len < buflen));
1533   return ret;
1534 }
1535 
1536 /*
1537  * DRBG uninstantiate function as required by SP800-90A - this function
1538  * frees all buffers and the DRBG handle
1539  *
1540  * @drbg DRBG state handle
1541  *
1542  * return
1543  * 	0 on success
1544  */
1545 static gpg_err_code_t
drbg_uninstantiate(drbg_state_t drbg)1546 drbg_uninstantiate (drbg_state_t drbg)
1547 {
1548   if (!drbg)
1549     return GPG_ERR_INV_ARG;
1550   drbg->d_ops->crypto_fini(drbg);
1551   xfree (drbg->V);
1552   drbg->V = NULL;
1553   xfree (drbg->C);
1554   drbg->C = NULL;
1555   drbg->reseed_ctr = 0;
1556   xfree (drbg->scratchpad);
1557   drbg->scratchpad = NULL;
1558   drbg->seeded = 0;
1559   drbg->pr = 0;
1560   drbg->seed_init_pid = 0;
1561   return 0;
1562 }
1563 
1564 /*
1565  * DRBG instantiation function as required by SP800-90A - this function
1566  * sets up the DRBG handle, performs the initial seeding and all sanity
1567  * checks required by SP800-90A
1568  *
1569  * @drbg memory of state -- if NULL, new memory is allocated
1570  * @pers Personalization string that is mixed into state, may be NULL -- note
1571  *	 the entropy is pulled by the DRBG internally unconditionally
1572  *	 as defined in SP800-90A. The additional input is mixed into
1573  *	 the state in addition to the pulled entropy.
1574  * @coreref reference to core
1575  * @flags Flags defining the requested DRBG type and cipher type. The flags
1576  * 	  are defined in drbg.h and may be XORed. Beware, if you XOR multiple
1577  * 	  cipher types together, the code picks the core on a first come first
1578  * 	  serve basis as it iterates through the available cipher cores and
1579  * 	  uses the one with the first match. The minimum required flags are:
1580  * 		cipher type flag
1581  *
1582  * return
1583  *	0 on success
1584  *	error value otherwise
1585  */
1586 static gpg_err_code_t
drbg_instantiate(drbg_state_t drbg,drbg_string_t * pers,int coreref,int pr)1587 drbg_instantiate (drbg_state_t drbg,
1588                   drbg_string_t *pers, int coreref, int pr)
1589 {
1590   gpg_err_code_t ret = GPG_ERR_ENOMEM;
1591   unsigned int sb_size = 0;
1592 
1593   if (!drbg)
1594     return GPG_ERR_INV_ARG;
1595 
1596   dbg (("DRBG: Initializing DRBG core %d with prediction resistance %s\n",
1597 	coreref, pr ? "enabled" : "disabled"));
1598   drbg->core = &drbg_cores[coreref];
1599   drbg->pr = pr;
1600   drbg->seeded = 0;
1601   if (drbg->core->flags & DRBG_HMAC)
1602     drbg->d_ops = &drbg_hmac_ops;
1603   else if (drbg->core->flags & DRBG_HASH_MASK)
1604     drbg->d_ops = &drbg_hash_ops;
1605   else if (drbg->core->flags & DRBG_CTR_MASK)
1606     drbg->d_ops = &drbg_ctr_ops;
1607   else
1608     return GPG_ERR_GENERAL;
1609   /* 9.1 step 1 is implicit with the selected DRBG type -- see
1610    * drbg_sec_strength() */
1611 
1612   /* 9.1 step 2 is implicit as caller can select prediction resistance
1613    * and the flag is copied into drbg->flags --
1614    * all DRBG types support prediction resistance */
1615 
1616   /* 9.1 step 4 is implicit in  drbg_sec_strength */
1617 
1618   ret = drbg->d_ops->crypto_init(drbg);
1619   if (ret)
1620     goto err;
1621 
1622   drbg->V = xcalloc_secure (1, drbg_statelen (drbg));
1623   if (!drbg->V)
1624     goto fini;
1625   drbg->C = xcalloc_secure (1, drbg_statelen (drbg));
1626   if (!drbg->C)
1627     goto fini;
1628   /* scratchpad is only generated for CTR and Hash */
1629   if (drbg->core->flags & DRBG_HMAC)
1630     sb_size = 0;
1631   else if (drbg->core->flags & DRBG_CTR_MASK)
1632     sb_size = drbg_statelen (drbg) + drbg_blocklen (drbg) +	/* temp */
1633       drbg_statelen (drbg) +	/* df_data */
1634       drbg_blocklen (drbg) +	/* pad */
1635       drbg_blocklen (drbg) +	/* iv */
1636       drbg_statelen (drbg) + drbg_blocklen (drbg);	/* temp */
1637   else
1638     sb_size = drbg_statelen (drbg);
1639 
1640   if (0 < sb_size)
1641     {
1642       drbg->scratchpad = xcalloc_secure (1, sb_size);
1643       if (!drbg->scratchpad)
1644 	goto fini;
1645     }
1646   dbg (("DRBG: state allocated with scratchpad size %u bytes\n", sb_size));
1647 
1648   /* 9.1 step 6 through 11 */
1649   ret = drbg_seed (drbg, pers, 0);
1650   if (ret)
1651     goto fini;
1652 
1653   dbg (("DRBG: core %d %s prediction resistance successfully initialized\n",
1654 	coreref, pr ? "with" : "without"));
1655   return 0;
1656 
1657  fini:
1658   drbg->d_ops->crypto_fini(drbg);
1659  err:
1660   drbg_uninstantiate (drbg);
1661   return ret;
1662 }
1663 
1664 /*
1665  * DRBG reseed function as required by SP800-90A
1666  *
1667  * @drbg DRBG state handle
1668  * @addtl Additional input that is mixed into state, may be NULL -- note
1669  * 		the entropy is pulled by the DRBG internally unconditionally
1670  * 		as defined in SP800-90A. The additional input is mixed into
1671  * 		the state in addition to the pulled entropy.
1672  *
1673  * return
1674  * 	0 on success
1675  * 	error value otherwise
1676  */
1677 static gpg_err_code_t
drbg_reseed(drbg_state_t drbg,drbg_string_t * addtl)1678 drbg_reseed (drbg_state_t drbg,drbg_string_t *addtl)
1679 {
1680   gpg_err_code_t ret = 0;
1681   ret = drbg_seed (drbg, addtl, 1);
1682   return ret;
1683 }
1684 
1685 
1686 
1687 /******************************************************************
1688  * Libgcrypt integration code.
1689  ******************************************************************/
1690 
1691 /***************************************************
1692  * Libgcrypt backend functions to the RNG API code.
1693  ***************************************************/
1694 
1695 static inline void
drbg_lock(void)1696 drbg_lock (void)
1697 {
1698   gpg_err_code_t ec;
1699 
1700   ec = gpgrt_lock_lock (&drbg_lock_var);
1701   if (ec)
1702     log_fatal ("failed to acquire the RNG lock: %s\n", gpg_strerror (ec));
1703 }
1704 
1705 static inline void
drbg_unlock(void)1706 drbg_unlock (void)
1707 {
1708   gpg_err_code_t ec;
1709 
1710   ec = gpgrt_lock_unlock (&drbg_lock_var);
1711   if (ec)
1712     log_fatal ("failed to release the RNG lock: %s\n", gpg_strerror (ec));
1713 }
1714 
1715 /* Basic initialization is required to initialize mutexes and
1716    do a few checks on the implementation.  */
1717 static void
basic_initialization(void)1718 basic_initialization (void)
1719 {
1720   static int initialized;
1721 
1722   if (initialized)
1723     return;
1724   initialized = 1;
1725 
1726   /* Make sure that we are still using the values we have
1727      traditionally used for the random levels.  */
1728   gcry_assert (GCRY_WEAK_RANDOM == 0
1729                && GCRY_STRONG_RANDOM == 1
1730                && GCRY_VERY_STRONG_RANDOM == 2);
1731 }
1732 
1733 /****** helper functions where lock must be held by caller *****/
1734 
1735 /* Check whether given flags are known to point to an applicable DRBG */
1736 static gpg_err_code_t
drbg_algo_available(u32 flags,int * coreref)1737 drbg_algo_available (u32 flags, int *coreref)
1738 {
1739   int i = 0;
1740   for (i = 0; ARRAY_SIZE (drbg_cores) > i; i++)
1741     {
1742       if ((drbg_cores[i].flags & DRBG_CIPHER_MASK) ==
1743 	  (flags & DRBG_CIPHER_MASK))
1744 	{
1745 	  *coreref = i;
1746 	  return 0;
1747 	}
1748     }
1749   return GPG_ERR_GENERAL;
1750 }
1751 
1752 static gpg_err_code_t
_drbg_init_internal(u32 flags,drbg_string_t * pers)1753 _drbg_init_internal (u32 flags, drbg_string_t *pers)
1754 {
1755   static u32 oldflags;
1756   gpg_err_code_t ret = 0;
1757   int coreref = 0;
1758   int pr = 0;
1759 
1760   /* If a caller provides 0 as flags, use the flags of the previous
1761    * initialization, otherwise use the current flags and remember them
1762    * for the next invocation.  If no flag is given and no global state
1763    * is set this is the first initialization and we set the default
1764    * type.
1765    */
1766   if (!flags && !drbg_state)
1767     flags = oldflags = DRBG_DEFAULT_TYPE;
1768   else if (!flags)
1769     flags = oldflags;
1770   else
1771     oldflags = flags;
1772 
1773   ret = drbg_algo_available (flags, &coreref);
1774   if (ret)
1775     return ret;
1776 
1777   if (drbg_state)
1778     {
1779       drbg_uninstantiate (drbg_state);
1780     }
1781   else
1782     {
1783       drbg_state = xtrycalloc_secure (1, sizeof *drbg_state);
1784       if (!drbg_state)
1785 	return gpg_err_code_from_syserror ();
1786     }
1787   if (flags & DRBG_PREDICTION_RESIST)
1788     pr = 1;
1789   ret = drbg_instantiate (drbg_state, pers, coreref, pr);
1790   if (ret)
1791     fips_signal_error ("DRBG cannot be initialized");
1792   else
1793     drbg_state->seed_init_pid = getpid ();
1794   return ret;
1795 }
1796 
1797 /************* calls available to common RNG code **************/
1798 
1799 /*
1800  * Initialize one DRBG invoked by the libgcrypt API
1801  */
1802 void
_gcry_rngdrbg_inititialize(int full)1803 _gcry_rngdrbg_inititialize (int full)
1804 {
1805   basic_initialization ();
1806   if (!full)
1807       return;
1808   drbg_lock ();
1809   if (!drbg_state)
1810     _drbg_init_internal (0, NULL);
1811   drbg_unlock ();
1812 }
1813 
1814 /*
1815  * Backend handler function for GCRYCTL_DRBG_REINIT
1816  *
1817  * Select a different DRBG type and initialize it.
1818  * Function checks whether requested DRBG type exists and returns an error in
1819  * case it does not. In case of an error, the previous instantiated DRBG is
1820  * left untouched and alive. Thus, in case of an error, a DRBG is always
1821  * available, even if it is not the chosen one.
1822  *
1823  * Re-initialization will be performed in any case regardless whether flags
1824  * or personalization string are set.
1825  *
1826  * If flags is NULL, do not change current DRBG.  If PERS is NULL and
1827  * NPERS is 0, re-initialize without personalization string.  If PERS
1828  * is not NULL NPERS must be one and PERS and the first ietm from the
1829  * bufer is take as personalization string.
1830  */
1831 gpg_err_code_t
_gcry_rngdrbg_reinit(const char * flagstr,gcry_buffer_t * pers,int npers)1832 _gcry_rngdrbg_reinit (const char *flagstr, gcry_buffer_t *pers, int npers)
1833 {
1834   gpg_err_code_t ret;
1835   unsigned int flags;
1836 
1837   /* If PERS is not given we expect NPERS to be zero; if given we
1838      expect a one-item array.  */
1839   if ((!pers && npers) || (pers && npers != 1))
1840     return GPG_ERR_INV_ARG;
1841 
1842   ret = parse_flag_string (flagstr, &flags);
1843   if (!ret)
1844     {
1845       dbg (("DRBG: reinitialize internal DRBG state with flags %u\n", flags));
1846       drbg_lock ();
1847       if (pers)
1848         {
1849           drbg_string_t persbuf;
1850 
1851           drbg_string_fill
1852             (&persbuf, (const unsigned char *)pers[0].data + pers[0].off,
1853              pers[0].len);
1854           ret = _drbg_init_internal (flags, &persbuf);
1855         }
1856       else
1857         ret = _drbg_init_internal (flags, NULL);
1858       drbg_unlock ();
1859     }
1860   return ret;
1861 }
1862 
1863 /* Try to close the FDs of the random gather module.  This is
1864  * currently only implemented for rndlinux. */
1865 void
_gcry_rngdrbg_close_fds(void)1866 _gcry_rngdrbg_close_fds (void)
1867 {
1868 #if USE_RNDLINUX
1869   drbg_lock ();
1870   _gcry_rndlinux_gather_random (NULL, 0, 0, 0);
1871   drbg_unlock ();
1872 #endif
1873 }
1874 
1875 /* Print some statistics about the RNG.  */
1876 void
_gcry_rngdrbg_dump_stats(void)1877 _gcry_rngdrbg_dump_stats (void)
1878 {
1879   /* Not yet implemented.  */
1880   /* Maybe dumping of reseed counter? */
1881 }
1882 
1883 /* This function returns true if no real RNG is available or the
1884  * quality of the RNG has been degraded for test purposes.  */
1885 int
_gcry_rngdrbg_is_faked(void)1886 _gcry_rngdrbg_is_faked (void)
1887 {
1888   return 0;			/* Faked random is not allowed.  */
1889 }
1890 
1891 /* Add BUFLEN bytes from BUF to the internal random pool.  QUALITY
1892  * should be in the range of 0..100 to indicate the goodness of the
1893  * entropy added, or -1 for goodness not known. */
1894 gcry_error_t
_gcry_rngdrbg_add_bytes(const void * buf,size_t buflen,int quality)1895 _gcry_rngdrbg_add_bytes (const void *buf, size_t buflen, int quality)
1896 {
1897   gpg_err_code_t ret = 0;
1898   drbg_string_t seed;
1899   (void) quality;
1900   _gcry_rngdrbg_inititialize (1); /* Auto-initialize if needed */
1901   if (!drbg_state)
1902     return GPG_ERR_GENERAL;
1903   drbg_string_fill (&seed, (unsigned char *) buf, buflen);
1904   drbg_lock ();
1905   ret = drbg_reseed (drbg_state, &seed);
1906   drbg_unlock ();
1907   return ret;
1908 }
1909 
1910 /* This function is to be used for all types of random numbers, including
1911  * nonces
1912  */
1913 void
_gcry_rngdrbg_randomize(void * buffer,size_t length,enum gcry_random_level level)1914 _gcry_rngdrbg_randomize (void *buffer, size_t length,
1915 		      enum gcry_random_level level)
1916 {
1917   (void) level;
1918   _gcry_rngdrbg_inititialize (1); /* Auto-initialize if needed */
1919   drbg_lock ();
1920   if (!drbg_state)
1921     {
1922       fips_signal_error ("DRBG is not initialized");
1923       goto bailout;
1924     }
1925 
1926   /* As reseeding changes the entire state of the DRBG, including any
1927    * key, either a re-init or a reseed is sufficient for a fork */
1928   if (drbg_state->seed_init_pid != getpid ())
1929     {
1930       /* We are in a child of us. Perform a reseeding. */
1931       if (drbg_reseed (drbg_state, NULL))
1932 	{
1933 	  fips_signal_error ("reseeding upon fork failed");
1934 	  log_fatal ("severe error getting random\n");
1935 	  goto bailout;
1936 	}
1937     }
1938   /* potential integer overflow is covered by drbg_generate which
1939    * ensures that length cannot overflow an unsigned int */
1940   if (0 < length)
1941     {
1942       if (!buffer)
1943 	goto bailout;
1944       if (drbg_generate_long (drbg_state, buffer, (unsigned int) length, NULL))
1945 	log_fatal ("No random numbers generated\n");
1946     }
1947   else
1948     {
1949       drbg_gen_t *data = (drbg_gen_t *)buffer;
1950       /* catch NULL pointer */
1951       if (!data || !data->outbuf)
1952 	{
1953 	  fips_signal_error ("No output buffer provided");
1954 	  goto bailout;
1955 	}
1956       if (drbg_generate_long (drbg_state, data->outbuf, data->outlen,
1957                               data->addtl))
1958 	log_fatal ("No random numbers generated\n");
1959     }
1960 
1961  bailout:
1962   drbg_unlock ();
1963   return;
1964 
1965 }
1966 
1967 /***************************************************************
1968  * Self-test code
1969  ***************************************************************/
1970 
1971 /*
1972  * Test vectors from
1973  * http://csrc.nist.gov/groups/STM/cavp/documents/drbg/drbgtestvectors.zip
1974  */
1975 struct gcry_drbg_test_vector drbg_test_pr[] = {
1976   {
1977     /* .flags = */ "sha256 pr" /* DRBG_PR_HASHSHA256 */,
1978     /* .entropy = */ (unsigned char *)
1979     "\x5d\xf2\x14\xbc\xf6\xb5\x4e\x0b\xf0\x0d\x6f\x2d"
1980     "\xe2\x01\x66\x7b\xd0\xa4\x73\xa4\x21\xdd\xb0\xc0"
1981     "\x51\x79\x09\xf4\xea\xa9\x08\xfa\xa6\x67\xe0\xe1"
1982     "\xd1\x88\xa8\xad\xee\x69\x74\xb3\x55\x06\x9b\xf6",
1983     /* .entropylen = */ 48,
1984     /* .entpra = */ (unsigned char *)
1985     "\xef\x48\x06\xa2\xc2\x45\xf1\x44\xfa\x34\x2c\xeb"
1986     "\x8d\x78\x3c\x09\x8f\x34\x72\x20\xf2\xe7\xfd\x13"
1987     "\x76\x0a\xf6\xdc\x3c\xf5\xc0\x15",
1988     /* .entprb = */ (unsigned char *)
1989     "\x4b\xbe\xe5\x24\xed\x6a\x2d\x0c\xdb\x73\x5e\x09"
1990     "\xf9\xad\x67\x7c\x51\x47\x8b\x6b\x30\x2a\xc6\xde"
1991     "\x76\xaa\x55\x04\x8b\x0a\x72\x95",
1992     /* .entprlen = */ 32,
1993     /* .addtla = */ (unsigned char *)
1994     "\xbe\x13\xdb\x2a\xe9\xa8\xfe\x09\x97\xe1\xce\x5d"
1995     "\xe8\xbb\xc0\x7c\x4f\xcb\x62\x19\x3f\x0f\xd2\xad"
1996     "\xa9\xd0\x1d\x59\x02\xc4\xff\x70",
1997     /* .addtlb = */ (unsigned char *)
1998     "\x6f\x96\x13\xe2\xa7\xf5\x6c\xfe\xdf\x66\xe3\x31"
1999     "\x63\x76\xbf\x20\x27\x06\x49\xf1\xf3\x01\x77\x41"
2000     "\x9f\xeb\xe4\x38\xfe\x67\x00\xcd",
2001     /* .addtllen = */ 32,
2002     /* .pers = */ NULL,
2003     /* .perslen = */ 0,
2004     /* .expected = */ (unsigned char *)
2005     "\x3b\x14\x71\x99\xa1\xda\xa0\x42\xe6\xc8\x85\x32"
2006     "\x70\x20\x32\x53\x9a\xbe\xd1\x1e\x15\xef\xfb\x4c"
2007     "\x25\x6e\x19\x3a\xf0\xb9\xcb\xde\xf0\x3b\xc6\x18"
2008     "\x4d\x85\x5a\x9b\xf1\xe3\xc2\x23\x03\x93\x08\xdb"
2009     "\xa7\x07\x4b\x33\x78\x40\x4d\xeb\x24\xf5\x6e\x81"
2010     "\x4a\x1b\x6e\xa3\x94\x52\x43\xb0\xaf\x2e\x21\xf4"
2011     "\x42\x46\x8e\x90\xed\x34\x21\x75\xea\xda\x67\xb6"
2012     "\xe4\xf6\xff\xc6\x31\x6c\x9a\x5a\xdb\xb3\x97\x13"
2013     "\x09\xd3\x20\x98\x33\x2d\x6d\xd7\xb5\x6a\xa8\xa9"
2014     "\x9a\x5b\xd6\x87\x52\xa1\x89\x2b\x4b\x9c\x64\x60"
2015     "\x50\x47\xa3\x63\x81\x16\xaf\x19",
2016     /* .expectedlen = */ 128,
2017     /* .entropyreseed = */ NULL,
2018     /* .entropyreseed_len = */ 0,
2019     /* .addtl_reseed = */ NULL,
2020     /* .addtl_reseed_len = */ 0
2021   },
2022   {
2023     /* flags = */ "hmac sha256 pr" /* DRBG_PR_HMACSHA256 */,
2024     /* .entropy = */ (unsigned char *)
2025     "\x13\x54\x96\xfc\x1b\x7d\x28\xf3\x18\xc9\xa7\x89"
2026     "\xb6\xb3\xc8\x72\xac\x00\xd4\x59\x36\x25\x05\xaf"
2027     "\xa5\xdb\x96\xcb\x3c\x58\x46\x87\xa5\xaa\xbf\x20"
2028     "\x3b\xfe\x23\x0e\xd1\xc7\x41\x0f\x3f\xc9\xb3\x67",
2029     /* .entropylen = */ 48,
2030     /* .entpra = */ (unsigned char *)
2031     "\xe2\xbd\xb7\x48\x08\x06\xf3\xe1\x93\x3c\xac\x79"
2032     "\xa7\x2b\x11\xda\xe3\x2e\xe1\x91\xa5\x02\x19\x57"
2033     "\x20\x28\xad\xf2\x60\xd7\xcd\x45",
2034     /* .entprb = */ (unsigned char *)
2035     "\x8b\xd4\x69\xfc\xff\x59\x95\x95\xc6\x51\xde\x71"
2036     "\x68\x5f\xfc\xf9\x4a\xab\xec\x5a\xcb\xbe\xd3\x66"
2037     "\x1f\xfa\x74\xd3\xac\xa6\x74\x60",
2038     /* .entprlen = */ 32,
2039     /* .addtla = */ NULL,
2040     /* .addtlb = */ NULL,
2041     /* .addtllen = */ 0,
2042     /* .pers = */ (unsigned char *)
2043     "\x64\xb6\xfc\x60\xbc\x61\x76\x23\x6d\x3f\x4a\x0f"
2044     "\xe1\xb4\xd5\x20\x9e\x70\xdd\x03\x53\x6d\xbf\xce"
2045     "\xcd\x56\x80\xbc\xb8\x15\xc8\xaa",
2046     /* .perslen = */ 32,
2047     /* .expected = */ (unsigned char *)
2048     "\x1f\x9e\xaf\xe4\xd2\x46\xb7\x47\x41\x4c\x65\x99"
2049     "\x01\xe9\x3b\xbb\x83\x0c\x0a\xb0\xc1\x3a\xe2\xb3"
2050     "\x31\x4e\xeb\x93\x73\xee\x0b\x26\xc2\x63\xa5\x75"
2051     "\x45\x99\xd4\x5c\x9f\xa1\xd4\x45\x87\x6b\x20\x61"
2052     "\x40\xea\x78\xa5\x32\xdf\x9e\x66\x17\xaf\xb1\x88"
2053     "\x9e\x2e\x23\xdd\xc1\xda\x13\x97\x88\xa5\xb6\x5e"
2054     "\x90\x14\x4e\xef\x13\xab\x5c\xd9\x2c\x97\x9e\x7c"
2055     "\xd7\xf8\xce\xea\x81\xf5\xcd\x71\x15\x49\x44\xce"
2056     "\x83\xb6\x05\xfb\x7d\x30\xb5\x57\x2c\x31\x4f\xfc"
2057     "\xfe\x80\xb6\xc0\x13\x0c\x5b\x9b\x2e\x8f\x3d\xfc"
2058     "\xc2\xa3\x0c\x11\x1b\x80\x5f\xf3",
2059     /* .expectedlen = */ 128,
2060     /* .entropyreseed = */ NULL,
2061     /* .entropyreseed_len = */ 0,
2062     /* .addtl_reseed = */ NULL,
2063     /* .addtl_reseed_len = */ 0
2064   },
2065   {
2066     /* .flags = */ "aes sym128 pr", /* DRBG_PR_CTRAES128 */
2067     /* .entropy = */ (unsigned char *)
2068     "\x92\x89\x8f\x31\xfa\x1c\xff\x6d\x18\x2f\x26\x06"
2069     "\x43\xdf\xf8\x18\xc2\xa4\xd9\x72\xc3\xb9\xb6\x97",
2070     /* .entropylen = */ 24,
2071     /* .entpra = */ (unsigned char *)
2072     "\x20\x72\x8a\x06\xf8\x6f\x8d\xd4\x41\xe2\x72\xb7"
2073     "\xc4\x2c\xe8\x10",
2074     /* .entprb = */ (unsigned char *)
2075     "\x3d\xb0\xf0\x94\xf3\x05\x50\x33\x17\x86\x3e\x22"
2076     "\x08\xf7\xa5\x01",
2077     /* .entprlen = */ 16,
2078     /* .addtla = */ (unsigned char *)
2079     "\x1a\x40\xfa\xe3\xcc\x6c\x7c\xa0\xf8\xda\xba\x59"
2080     "\x23\x6d\xad\x1d",
2081     /* .addtlb = */ (unsigned char *)
2082     "\x9f\x72\x76\x6c\xc7\x46\xe5\xed\x2e\x53\x20\x12"
2083     "\xbc\x59\x31\x8c",
2084     /* .addtllen = */ 16,
2085     /* .pers = */ (unsigned char *)
2086     "\xea\x65\xee\x60\x26\x4e\x7e\xb6\x0e\x82\x68\xc4"
2087     "\x37\x3c\x5c\x0b",
2088     /* .perslen = */ 16,
2089     /* .expected = */ (unsigned char *)
2090     "\x5a\x35\x39\x87\x0f\x4d\x22\xa4\x09\x24\xee\x71"
2091     "\xc9\x6f\xac\x72\x0a\xd6\xf0\x88\x82\xd0\x83\x28"
2092     "\x73\xec\x3f\x93\xd8\xab\x45\x23\xf0\x7e\xac\x45"
2093     "\x14\x5e\x93\x9f\xb1\xd6\x76\x43\x3d\xb6\xe8\x08"
2094     "\x88\xf6\xda\x89\x08\x77\x42\xfe\x1a\xf4\x3f\xc4"
2095     "\x23\xc5\x1f\x68",
2096     /* .expectedlen = */ 64,
2097     /* .entropyreseed = */ NULL,
2098     /* .entropyreseed_len = */ 0,
2099     /* .addtl_reseed = */ NULL,
2100     /* .addtl_reseed_len = */ 0
2101    }
2102 };
2103 
2104 struct gcry_drbg_test_vector drbg_test_nopr[] = {
2105   {
2106     /* .flags = */ "sha256" /* DRBG_NOPR_HASHSHA256 */,
2107     /* .entropy = */ (unsigned char *)
2108     "\x73\xd3\xfb\xa3\x94\x5f\x2b\x5f\xb9\x8f\xf6\x9c"
2109     "\x8a\x93\x17\xae\x19\xc3\x4c\xc3\xd6\xca\xa3\x2d"
2110     "\x16\xfc\x42\xd2\x2d\xd5\x6f\x56\xcc\x1d\x30\xff"
2111     "\x9e\x06\x3e\x09\xce\x58\xe6\x9a\x35\xb3\xa6\x56",
2112     /* .entropylen = */ 48,
2113     /* .entpra = */ NULL,
2114     /* .entprb = */ NULL,
2115     /* .entprlen = */ 0,
2116     /* .addtla = */ (unsigned char *)
2117     "\xf4\xd5\x98\x3d\xa8\xfc\xfa\x37\xb7\x54\x67\x73"
2118     "\xc7\xc3\xdd\x47\x34\x71\x02\x5d\xc1\xa0\xd3\x10"
2119     "\xc1\x8b\xbd\xf5\x66\x34\x6f\xdd",
2120     /* .addtlb = */ (unsigned char *)
2121     "\xf7\x9e\x6a\x56\x0e\x73\xe9\xd9\x7a\xd1\x69\xe0"
2122     "\x6f\x8c\x55\x1c\x44\xd1\xce\x6f\x28\xcc\xa4\x4d"
2123     "\xa8\xc0\x85\xd1\x5a\x0c\x59\x40",
2124     /* .addtllen = */ 32,
2125     /* .pers = */ NULL,
2126     /* .perslen = */ 0,
2127     /* .expected = */ (unsigned char *)
2128     "\x71\x7b\x93\x46\x1a\x40\xaa\x35\xa4\xaa\xc5\xe7"
2129     "\x6d\x5b\x5b\x8a\xa0\xdf\x39\x7d\xae\x71\x58\x5b"
2130     "\x3c\x7c\xb4\xf0\x89\xfa\x4a\x8c\xa9\x5c\x54\xc0"
2131     "\x40\xdf\xbc\xce\x26\x81\x34\xf8\xba\x7d\x1c\xe8"
2132     "\xad\x21\xe0\x74\xcf\x48\x84\x30\x1f\xa1\xd5\x4f"
2133     "\x81\x42\x2f\xf4\xdb\x0b\x23\xf8\x73\x27\xb8\x1d"
2134     "\x42\xf8\x44\x58\xd8\x5b\x29\x27\x0a\xf8\x69\x59"
2135     "\xb5\x78\x44\xeb\x9e\xe0\x68\x6f\x42\x9a\xb0\x5b"
2136     "\xe0\x4e\xcb\x6a\xaa\xe2\xd2\xd5\x33\x25\x3e\xe0"
2137     "\x6c\xc7\x6a\x07\xa5\x03\x83\x9f\xe2\x8b\xd1\x1c"
2138     "\x70\xa8\x07\x59\x97\xeb\xf6\xbe",
2139     /* .expectedlen = */ 128,
2140     /* .entropyreseed = */ NULL,
2141     /* .entropyreseed_len = */ 0,
2142     /* .addtl_reseed = */ NULL,
2143     /* .addtl_reseed_len = */ 0
2144   },
2145   {
2146     /* .flags = */ "hmac sha256" /* DRBG_NOPR_HMACSHA256 */,
2147     /* .entropy = */ (unsigned char *)
2148     "\x8d\xf0\x13\xb4\xd1\x03\x52\x30\x73\x91\x7d\xdf"
2149     "\x6a\x86\x97\x93\x05\x9e\x99\x43\xfc\x86\x54\x54"
2150     "\x9e\x7a\xb2\x2f\x7c\x29\xf1\x22\xda\x26\x25\xaf"
2151     "\x2d\xdd\x4a\xbc\xce\x3c\xf4\xfa\x46\x59\xd8\x4e",
2152     /* .entropylen = */ 48,
2153     /* .entpra = */ NULL,
2154     /* .entprb = */ NULL,
2155     /* .entprlen = */ 0,
2156     /* .addtla = */ NULL,
2157     /* .addtlb = */ NULL,
2158     /* .addtllen = */ 0,
2159     /* .pers = */ (unsigned char *)
2160     "\xb5\x71\xe6\x6d\x7c\x33\x8b\xc0\x7b\x76\xad\x37"
2161     "\x57\xbb\x2f\x94\x52\xbf\x7e\x07\x43\x7a\xe8\x58"
2162     "\x1c\xe7\xbc\x7c\x3a\xc6\x51\xa9",
2163     /* .perslen = */ 32,
2164     /* .expected = */ (unsigned char *)
2165     "\xb9\x1c\xba\x4c\xc8\x4f\xa2\x5d\xf8\x61\x0b\x81"
2166     "\xb6\x41\x40\x27\x68\xa2\x09\x72\x34\x93\x2e\x37"
2167     "\xd5\x90\xb1\x15\x4c\xbd\x23\xf9\x74\x52\xe3\x10"
2168     "\xe2\x91\xc4\x51\x46\x14\x7f\x0d\xa2\xd8\x17\x61"
2169     "\xfe\x90\xfb\xa6\x4f\x94\x41\x9c\x0f\x66\x2b\x28"
2170     "\xc1\xed\x94\xda\x48\x7b\xb7\xe7\x3e\xec\x79\x8f"
2171     "\xbc\xf9\x81\xb7\x91\xd1\xbe\x4f\x17\x7a\x89\x07"
2172     "\xaa\x3c\x40\x16\x43\xa5\xb6\x2b\x87\xb8\x9d\x66"
2173     "\xb3\xa6\x0e\x40\xd4\xa8\xe4\xe9\xd8\x2a\xf6\xd2"
2174     "\x70\x0e\x6f\x53\x5c\xdb\x51\xf7\x5c\x32\x17\x29"
2175     "\x10\x37\x41\x03\x0c\xcc\x3a\x56",
2176     /* .expectedlen = */ 128,
2177     /* .entropyreseed = */ NULL,
2178     /* .entropyreseed_len = */ 0,
2179     /* .addtl_reseed = */ NULL,
2180     /* .addtl_reseed_len = */ 0
2181   },
2182   {
2183     /* .flags = */ "aes sym128" /* DRBG_NOPR_CTRAES128 */,
2184     /* .entropy = */ (unsigned char *)
2185     "\xc0\x70\x1f\x92\x50\x75\x8f\xcd\xf2\xbe\x73\x98"
2186     "\x80\xdb\x66\xeb\x14\x68\xb4\xa5\x87\x9c\x2d\xa6",
2187     /* .entropylen = */ 24,
2188     /* .entpra = */ NULL,
2189     /* .entprb = */ NULL,
2190     /* .entprlen = */ 0,
2191     /* .addtla = */ (unsigned char *)
2192     "\xf9\x01\xf8\x16\x7a\x1d\xff\xde\x8e\x3c\x83\xe2"
2193     "\x44\x85\xe7\xfe",
2194     /* .addtlb = */ (unsigned char *)
2195     "\x17\x1c\x09\x38\xc2\x38\x9f\x97\x87\x60\x55\xb4"
2196     "\x82\x16\x62\x7f",
2197     /* .addtllen = */ 16,
2198     /* .pers = */ (unsigned char *)
2199     "\x80\x08\xae\xe8\xe9\x69\x40\xc5\x08\x73\xc7\x9f"
2200     "\x8e\xcf\xe0\x02",
2201     /* .perslen = */ 16,
2202     /* .expected = */ (unsigned char *)
2203     "\x97\xc0\xc0\xe5\xa0\xcc\xf2\x4f\x33\x63\x48\x8a"
2204     "\xdb\x13\x0a\x35\x89\xbf\x80\x65\x62\xee\x13\x95"
2205     "\x7c\x33\xd3\x7d\xf4\x07\x77\x7a\x2b\x65\x0b\x5f"
2206     "\x45\x5c\x13\xf1\x90\x77\x7f\xc5\x04\x3f\xcc\x1a"
2207     "\x38\xf8\xcd\x1b\xbb\xd5\x57\xd1\x4a\x4c\x2e\x8a"
2208     "\x2b\x49\x1e\x5c",
2209     /* .expectedlen = */ 64,
2210     /* .entropyreseed = */ NULL,
2211     /* .entropyreseed_len = */ 0,
2212     /* .addtl_reseed = */ NULL,
2213     /* .addtl_reseed_len = */ 0
2214   },
2215   {
2216     /* .flags = */ "sha1" /* DRBG_NOPR_HASHSHA1 */,
2217     /* .entropy = */ (unsigned char *)
2218     "\x16\x10\xb8\x28\xcc\xd2\x7d\xe0\x8c\xee\xa0\x32"
2219     "\xa2\x0e\x92\x08\x49\x2c\xf1\x70\x92\x42\xf6\xb5",
2220     /* .entropylen = */ 24,
2221     /* .entpra = */ NULL,
2222     /* .entprb = */ NULL,
2223     /* .entprlen = */ 0,
2224     /* .addtla = */ NULL,
2225     /* .addtlb = */ NULL,
2226     /* .addtllen = */ 0,
2227     /* .pers = */ NULL,
2228     /* .perslen = */ 0,
2229     /* .expected = */ (unsigned char *)
2230     "\x56\xf3\x3d\x4f\xdb\xb9\xa5\xb6\x4d\x26\x23\x44"
2231     "\x97\xe9\xdc\xb8\x77\x98\xc6\x8d\x08\xf7\xc4\x11"
2232     "\x99\xd4\xbd\xdf\x97\xeb\xbf\x6c\xb5\x55\x0e\x5d"
2233     "\x14\x9f\xf4\xd5\xbd\x0f\x05\xf2\x5a\x69\x88\xc1"
2234     "\x74\x36\x39\x62\x27\x18\x4a\xf8\x4a\x56\x43\x35"
2235     "\x65\x8e\x2f\x85\x72\xbe\xa3\x33\xee\xe2\xab\xff"
2236     "\x22\xff\xa6\xde\x3e\x22\xac\xa2",
2237     /* .expectedlen = */ 80,
2238     /* .entropyreseed = */ (unsigned char *)
2239     "\x72\xd2\x8c\x90\x8e\xda\xf9\xa4\xd1\xe5\x26\xd8"
2240     "\xf2\xde\xd5\x44",
2241     /* .entropyreseed_len = */ 16,
2242     /* .addtl_reseed = */ NULL,
2243     /* .addtl_reseed_len = */ 0
2244   },
2245   {
2246     /* .flags = */ "sha1" /* DRBG_NOPR_HASHSHA1 */,
2247     /* .entropy = */ (unsigned char *)
2248     "\xd9\xba\xb5\xce\xdc\xa9\x6f\x61\x78\xd6\x45\x09"
2249     "\xa0\xdf\xdc\x5e\xda\xd8\x98\x94\x14\x45\x0e\x01",
2250     /* .entropylen = */ 24,
2251     /* .entpra = */ NULL,
2252     /* .entprb = */ NULL,
2253     /* .entprlen = */ 0,
2254     /* .addtla = */ (unsigned char *)
2255     "\x04\xfa\x28\x95\xaa\x5a\x6f\x8c\x57\x43\x34\x3b"
2256     "\x80\x5e\x5e\xa4",
2257     /* .addtlb = */ (unsigned char *)
2258     "\xdf\x5d\xc4\x59\xdf\xf0\x2a\xa2\xf0\x52\xd7\x21"
2259     "\xec\x60\x72\x30",
2260     /* .addtllen = */ 16,
2261     /* .pers = */ NULL,
2262     /* .perslen = */ 0,
2263     /* .expected = */ (unsigned char *)
2264     "\xc4\x8b\x89\xf9\xda\x3f\x74\x82\x45\x55\x5d\x5d"
2265     "\x03\x3b\x69\x3d\xd7\x1a\x4d\xf5\x69\x02\x05\xce"
2266     "\xfc\xd7\x20\x11\x3c\xc2\x4e\x09\x89\x36\xff\x5e"
2267     "\x77\xb5\x41\x53\x58\x70\xb3\x39\x46\x8c\xdd\x8d"
2268     "\x6f\xaf\x8c\x56\x16\x3a\x70\x0a\x75\xb2\x3e\x59"
2269     "\x9b\x5a\xec\xf1\x6f\x3b\xaf\x6d\x5f\x24\x19\x97"
2270     "\x1f\x24\xf4\x46\x72\x0f\xea\xbe",
2271     /* .expectedlen = */ 80,
2272     /* .entropyreseed = */ (unsigned char *)
2273     "\xc6\xba\xd0\x74\xc5\x90\x67\x86\xf5\xe1\xf3\x20"
2274     "\x99\xf5\xb4\x91",
2275     /* .entropyreseed_len = */ 16,
2276     /* .addtl_reseed = */ (unsigned char *)
2277     "\x3e\x6b\xf4\x6f\x4d\xaa\x38\x25\xd7\x19\x4e\x69"
2278     "\x4e\x77\x52\xf7",
2279     /* .addtl_reseed_len = */ 16
2280   }
2281 };
2282 
2283 
2284 /*
2285  * Tests implement the CAVS test approach as documented in
2286  * http://csrc.nist.gov/groups/STM/cavp/documents/drbg/DRBGVS.pdf
2287  */
2288 
2289 /*
2290  * CAVS test
2291  *
2292  * This function is not static as it is needed for as a private API
2293  * call for the CAVS test tool.
2294  */
2295 gpg_err_code_t
_gcry_rngdrbg_cavs_test(struct gcry_drbg_test_vector * test,unsigned char * buf)2296 _gcry_rngdrbg_cavs_test (struct gcry_drbg_test_vector *test, unsigned char *buf)
2297 {
2298   gpg_err_code_t ret = 0;
2299   drbg_state_t drbg = NULL;
2300   struct drbg_test_data_s test_data;
2301   drbg_string_t addtl, pers, testentropy;
2302   int coreref = 0;
2303   int pr = 0;
2304   u32 flags;
2305 
2306   ret = parse_flag_string (test->flagstr, &flags);
2307   if (ret)
2308     goto outbuf;
2309 
2310   ret = drbg_algo_available (flags, &coreref);
2311   if (ret)
2312     goto outbuf;
2313 
2314   drbg = xtrycalloc_secure (1, sizeof *drbg);
2315   if (!drbg)
2316     {
2317       ret = gpg_err_code_from_syserror ();
2318       goto outbuf;
2319     }
2320 
2321   if ((flags & DRBG_PREDICTION_RESIST))
2322     pr = 1;
2323 
2324   test_data.testentropy = &testentropy;
2325   drbg_string_fill (&testentropy, test->entropy, test->entropylen);
2326   drbg->test_data = &test_data;
2327   drbg_string_fill (&pers, test->pers, test->perslen);
2328   ret = drbg_instantiate (drbg, &pers, coreref, pr);
2329   if (ret)
2330     goto outbuf;
2331 
2332   if (test->entropyreseed)
2333     {
2334       drbg_string_fill (&testentropy, test->entropyreseed,
2335 			     test->entropyreseed_len);
2336       drbg_string_fill (&addtl, test->addtl_reseed,
2337 			     test->addtl_reseed_len);
2338       if (drbg_reseed (drbg, &addtl))
2339 	goto outbuf;
2340     }
2341 
2342   drbg_string_fill (&addtl, test->addtla, test->addtllen);
2343   if (test->entpra)
2344     {
2345       drbg_string_fill (&testentropy, test->entpra, test->entprlen);
2346       drbg->test_data = &test_data;
2347     }
2348   drbg_generate_long (drbg, buf, test->expectedlen, &addtl);
2349 
2350   drbg_string_fill (&addtl, test->addtlb, test->addtllen);
2351   if (test->entprb)
2352     {
2353       drbg_string_fill (&testentropy, test->entprb, test->entprlen);
2354       drbg->test_data = &test_data;
2355     }
2356   drbg_generate_long (drbg, buf, test->expectedlen, &addtl);
2357   drbg_uninstantiate (drbg);
2358 
2359  outbuf:
2360   xfree (drbg);
2361   return ret;
2362 }
2363 
2364 /*
2365  * Invoke the CAVS test and perform the final check whether the
2366  * calculated random value matches the expected one.
2367  *
2368  * This function is not static as it is needed for as a private API
2369  * call for the CAVS test tool.
2370  */
2371 gpg_err_code_t
_gcry_rngdrbg_healthcheck_one(struct gcry_drbg_test_vector * test)2372 _gcry_rngdrbg_healthcheck_one (struct gcry_drbg_test_vector * test)
2373 {
2374   gpg_err_code_t ret = GPG_ERR_ENOMEM;
2375   unsigned char *buf = xcalloc_secure (1, test->expectedlen);
2376   if (!buf)
2377     return GPG_ERR_ENOMEM;
2378 
2379   ret = _gcry_rngdrbg_cavs_test (test, buf);
2380   /* FIXME: The next line is wrong.   */
2381   ret = memcmp (test->expected, buf, test->expectedlen);
2382 
2383   xfree (buf);
2384   return ret;
2385 }
2386 
2387 /*
2388  * Tests as defined in 11.3.2 in addition to the cipher tests: testing
2389  * of the error handling.
2390  *
2391  * Note, testing the reseed counter is not done as an automatic reseeding
2392  * is performed in drbg_generate when the reseed counter is too large.
2393  */
2394 static gpg_err_code_t
drbg_healthcheck_sanity(struct gcry_drbg_test_vector * test)2395 drbg_healthcheck_sanity (struct gcry_drbg_test_vector *test)
2396 {
2397   unsigned int len = 0;
2398   drbg_state_t drbg = NULL;
2399   gpg_err_code_t ret = GPG_ERR_GENERAL;
2400   gpg_err_code_t tmpret = GPG_ERR_GENERAL;
2401   struct drbg_test_data_s test_data;
2402   drbg_string_t addtl, testentropy;
2403   int coreref = 0;
2404   unsigned char *buf = NULL;
2405   size_t max_addtllen, max_request_bytes;
2406   u32 flags;
2407 
2408   /* only perform test in FIPS mode */
2409   if (0 == fips_mode ())
2410     return 0;
2411 
2412   ret = parse_flag_string (test->flagstr, &flags);
2413   if (ret)
2414     return ret;
2415   ret = GPG_ERR_GENERAL; /* Fixme: Improve handling of RET.  */
2416 
2417   buf = xtrycalloc_secure (1, test->expectedlen);
2418   if (!buf)
2419     return gpg_err_code_from_syserror ();
2420   tmpret = drbg_algo_available (flags, &coreref);
2421   if (tmpret)
2422     goto outbuf;
2423   drbg = xtrycalloc_secure (1, sizeof *drbg);
2424   if (!drbg)
2425     {
2426       ret = gpg_err_code_from_syserror ();
2427       goto outbuf;
2428     }
2429 
2430   /* if the following tests fail, it is likely that there is a buffer
2431    * overflow and we get a SIGSEV */
2432   ret = drbg_instantiate (drbg, NULL, coreref, 1);
2433   if (ret)
2434     goto outbuf;
2435   max_addtllen = drbg_max_addtl ();
2436   max_request_bytes = drbg_max_request_bytes ();
2437   /* overflow addtllen with additional info string */
2438   drbg_string_fill (&addtl, test->addtla, (max_addtllen + 1));
2439   len = drbg_generate (drbg, buf, test->expectedlen, &addtl);
2440   if (len)
2441     goto outdrbg;
2442 
2443   /* overflow max_bits */
2444   len = drbg_generate (drbg, buf, (max_request_bytes + 1), NULL);
2445   if (len)
2446     goto outdrbg;
2447   drbg_uninstantiate (drbg);
2448 
2449   /* test failing entropy source as defined in 11.3.2 */
2450   test_data.testentropy = NULL;
2451   test_data.fail_seed_source = 1;
2452   drbg->test_data = &test_data;
2453   tmpret = drbg_instantiate (drbg, NULL, coreref, 0);
2454   if (!tmpret)
2455     goto outdrbg;
2456   test_data.fail_seed_source = 0;
2457 
2458   test_data.testentropy = &testentropy;
2459   drbg_string_fill (&testentropy, test->entropy, test->entropylen);
2460   /* overflow max addtllen with personalization string */
2461   tmpret = drbg_instantiate (drbg, &addtl, coreref, 0);
2462   if (!tmpret)
2463     goto outdrbg;
2464 
2465   dbg (("DRBG: Sanity tests for failure code paths successfully completed\n"));
2466   ret = 0;
2467 
2468  outdrbg:
2469   drbg_uninstantiate (drbg);
2470  outbuf:
2471   xfree (buf);
2472   xfree (drbg);
2473   return ret;
2474 }
2475 
2476 /*
2477  * DRBG Healthcheck function as required in SP800-90A
2478  *
2479  * return:
2480  * 	0 on success (all tests pass)
2481  * 	>0 on error (return code indicate the number of failures)
2482  */
2483 static int
drbg_healthcheck(void)2484 drbg_healthcheck (void)
2485 {
2486   int ret = 0;
2487   ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_nopr[0]);
2488   ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_nopr[1]);
2489   ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_nopr[2]);
2490   ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_nopr[3]);
2491   ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_nopr[4]);
2492   ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_pr[0]);
2493   ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_pr[1]);
2494   ret += _gcry_rngdrbg_healthcheck_one (&drbg_test_pr[2]);
2495   ret += drbg_healthcheck_sanity (&drbg_test_nopr[0]);
2496   return ret;
2497 }
2498 
2499 /* Run the self-tests.  */
2500 gcry_error_t
_gcry_rngdrbg_selftest(selftest_report_func_t report)2501 _gcry_rngdrbg_selftest (selftest_report_func_t report)
2502 {
2503   gcry_err_code_t ec;
2504   const char *errtxt = NULL;
2505   drbg_lock ();
2506   if (0 != drbg_healthcheck ())
2507     errtxt = "RNG output does not match known value";
2508   drbg_unlock ();
2509   if (report && errtxt)
2510     report ("random", 0, "KAT", errtxt);
2511   ec = errtxt ? GPG_ERR_SELFTEST_FAILED : 0;
2512   return gpg_error (ec);
2513 }
2514 
2515 /***************************************************************
2516  * Cipher invocations requested by DRBG
2517  ***************************************************************/
2518 
2519 static gpg_err_code_t
drbg_hash_init(drbg_state_t drbg)2520 drbg_hash_init (drbg_state_t drbg)
2521 {
2522   gcry_md_hd_t hd;
2523   gpg_error_t err;
2524 
2525   err = _gcry_md_open (&hd, drbg->core->backend_cipher, 0);
2526   if (err)
2527     return err;
2528 
2529   drbg->priv_data = hd;
2530 
2531   return 0;
2532 }
2533 
2534 static gpg_err_code_t
drbg_hmac_init(drbg_state_t drbg)2535 drbg_hmac_init (drbg_state_t drbg)
2536 {
2537   gcry_md_hd_t hd;
2538   gpg_error_t err;
2539 
2540   err = _gcry_md_open (&hd, drbg->core->backend_cipher, GCRY_MD_FLAG_HMAC);
2541   if (err)
2542     return err;
2543 
2544   drbg->priv_data = hd;
2545 
2546   return 0;
2547 }
2548 
2549 static gpg_err_code_t
drbg_hmac_setkey(drbg_state_t drbg,const unsigned char * key)2550 drbg_hmac_setkey (drbg_state_t drbg, const unsigned char *key)
2551 {
2552   gcry_md_hd_t hd = (gcry_md_hd_t)drbg->priv_data;
2553 
2554   return _gcry_md_setkey (hd, key, drbg_statelen (drbg));
2555 }
2556 
2557 static void
drbg_hash_fini(drbg_state_t drbg)2558 drbg_hash_fini (drbg_state_t drbg)
2559 {
2560   gcry_md_hd_t hd = (gcry_md_hd_t)drbg->priv_data;
2561 
2562   _gcry_md_close (hd);
2563 }
2564 
2565 static byte *
drbg_hash(drbg_state_t drbg,const drbg_string_t * buf)2566 drbg_hash (drbg_state_t drbg, const drbg_string_t *buf)
2567 {
2568   gcry_md_hd_t hd = (gcry_md_hd_t)drbg->priv_data;
2569 
2570   _gcry_md_reset(hd);
2571   for (; NULL != buf; buf = buf->next)
2572     _gcry_md_write (hd, buf->buf, buf->len);
2573   _gcry_md_final (hd);
2574   return _gcry_md_read (hd, drbg->core->backend_cipher);
2575 }
2576 
2577 static void
drbg_sym_fini(drbg_state_t drbg)2578 drbg_sym_fini (drbg_state_t drbg)
2579 {
2580   gcry_cipher_hd_t hd = (gcry_cipher_hd_t)drbg->priv_data;
2581 
2582   if (hd)
2583     _gcry_cipher_close (hd);
2584   if (drbg->ctr_handle)
2585     _gcry_cipher_close (drbg->ctr_handle);
2586 }
2587 
2588 static gpg_err_code_t
drbg_sym_init(drbg_state_t drbg)2589 drbg_sym_init (drbg_state_t drbg)
2590 {
2591   gcry_cipher_hd_t hd;
2592   gpg_error_t err;
2593 
2594   err = _gcry_cipher_open (&hd, drbg->core->backend_cipher,
2595 			   GCRY_CIPHER_MODE_ECB, 0);
2596   if (err)
2597     {
2598       drbg_sym_fini (drbg);
2599       return err;
2600     }
2601   drbg->priv_data = hd;
2602 
2603   err = _gcry_cipher_open (&drbg->ctr_handle, drbg->core->backend_cipher,
2604 			   GCRY_CIPHER_MODE_CTR, 0);
2605   if (err)
2606     {
2607       drbg_sym_fini (drbg);
2608       return err;
2609     }
2610 
2611 
2612   if (drbg_blocklen (drbg) !=
2613       _gcry_cipher_get_algo_blklen (drbg->core->backend_cipher))
2614     {
2615       drbg_sym_fini (drbg);
2616       return -GPG_ERR_NO_ERROR;
2617     }
2618 
2619   return 0;
2620 }
2621 
2622 static gpg_err_code_t
drbg_sym_setkey(drbg_state_t drbg,const unsigned char * key)2623 drbg_sym_setkey (drbg_state_t drbg, const unsigned char *key)
2624 {
2625   gcry_cipher_hd_t hd = (gcry_cipher_hd_t)drbg->priv_data;
2626 
2627   return _gcry_cipher_setkey (hd, key, drbg_keylen (drbg));
2628 }
2629 
2630 static gpg_err_code_t
drbg_sym(drbg_state_t drbg,unsigned char * outval,const drbg_string_t * buf)2631 drbg_sym (drbg_state_t drbg, unsigned char *outval, const drbg_string_t *buf)
2632 {
2633   gcry_cipher_hd_t hd = (gcry_cipher_hd_t)drbg->priv_data;
2634 
2635   _gcry_cipher_reset(hd);
2636   if (drbg_blocklen (drbg) < buf->len)
2637     return -GPG_ERR_NO_ERROR;
2638   /* in is only component */
2639   return _gcry_cipher_encrypt (hd, outval, drbg_blocklen (drbg), buf->buf,
2640 			       buf->len);
2641 }
2642 
2643 static gpg_err_code_t
drbg_sym_ctr(drbg_state_t drbg,const unsigned char * inbuf,unsigned int inbuflen,unsigned char * outbuf,unsigned int outbuflen)2644 drbg_sym_ctr (drbg_state_t drbg,
2645 	      const unsigned char *inbuf, unsigned int inbuflen,
2646 	      unsigned char *outbuf, unsigned int outbuflen)
2647 {
2648   gpg_error_t err;
2649 
2650   _gcry_cipher_reset(drbg->ctr_handle);
2651   err = _gcry_cipher_setctr(drbg->ctr_handle, drbg->V, drbg_blocklen (drbg));
2652   if (err)
2653     return err;
2654 
2655   while (outbuflen)
2656     {
2657        unsigned int cryptlen = (inbuflen > outbuflen) ? outbuflen : inbuflen;
2658 
2659        err = _gcry_cipher_encrypt (drbg->ctr_handle, outbuf, cryptlen, inbuf,
2660 				   cryptlen);
2661        if (err)
2662          return err;
2663 
2664        outbuflen -= cryptlen;
2665        outbuf += cryptlen;
2666     }
2667   return _gcry_cipher_getctr(drbg->ctr_handle, drbg->V, drbg_blocklen (drbg));
2668 }
2669