-fix paths
[oweals/gnunet.git] / src / util / crypto_random.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2003, 2004, 2005, 2006, 2012 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19
20 */
21
22 /**
23  * @file util/crypto_random.c
24  * @brief functions to gather random numbers
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include <gcrypt.h>
30
31 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
32
33 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
34
35
36 /* TODO: ndurner, move this to plibc? */
37 /* The code is derived from glibc, obviously */
38 #if !HAVE_RANDOM || !HAVE_SRANDOM
39 #ifdef RANDOM
40 #undef RANDOM
41 #endif
42 #ifdef SRANDOM
43 #undef SRANDOM
44 #endif
45 #define RANDOM() glibc_weak_rand32()
46 #define SRANDOM(s) glibc_weak_srand32(s)
47 #if defined(RAND_MAX)
48 #undef RAND_MAX
49 #endif
50 #define RAND_MAX 0x7fffffff /* Hopefully this is correct */
51
52
53 static int32_t glibc_weak_rand32_state = 1;
54
55
56 void
57 glibc_weak_srand32 (int32_t s)
58 {
59   glibc_weak_rand32_state = s;
60 }
61
62
63 int32_t
64 glibc_weak_rand32 ()
65 {
66   int32_t val = glibc_weak_rand32_state;
67
68   val = ((glibc_weak_rand32_state * 1103515245) + 12345) & 0x7fffffff;
69   glibc_weak_rand32_state = val;
70   return val;
71 }
72 #endif
73
74 /**
75  * Create a cryptographically weak pseudo-random number in the interval of 0 to 1.
76  *
77  * @return number between 0 and 1.
78  */
79 static double
80 get_weak_random ()
81 {
82   return ((double) RANDOM () / RAND_MAX);
83 }
84
85
86 /**
87  * Seed a weak random generator. Only GNUNET_CRYPTO_QUALITY_WEAK-mode generator
88  * can be seeded.
89  *
90  * @param seed the seed to use
91  */
92 void
93 GNUNET_CRYPTO_seed_weak_random (int32_t seed)
94 {
95   SRANDOM (seed);
96 }
97
98 /**
99  * @ingroup crypto
100  * Fill block with a random values.
101  *
102  * @param mode desired quality of the random number
103  * @param buffer the buffer to fill
104  * @param length buffer length
105  */
106 void
107 GNUNET_CRYPTO_random_block (enum GNUNET_CRYPTO_Quality mode, void *buffer, size_t length)
108 {
109 #ifdef gcry_fast_random_poll
110   static unsigned int invokeCount;
111 #endif
112   switch (mode)
113   {
114   case GNUNET_CRYPTO_QUALITY_STRONG:
115     /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
116 #ifdef gcry_fast_random_poll
117     if ((invokeCount++ % 256) == 0)
118       gcry_fast_random_poll ();
119 #endif
120     gcry_randomize (buffer, length, GCRY_STRONG_RANDOM);
121     return;
122   case GNUNET_CRYPTO_QUALITY_NONCE:
123     gcry_create_nonce (buffer, length);
124     return;
125   case GNUNET_CRYPTO_QUALITY_WEAK:
126     /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
127 #ifdef gcry_fast_random_poll
128     if ((invokeCount++ % 256) == 0)
129       gcry_fast_random_poll ();
130 #endif
131     gcry_randomize (buffer, length, GCRY_WEAK_RANDOM);
132     return;
133     return;
134   default:
135     GNUNET_assert (0);
136   }
137 }
138
139
140 /**
141  * Produce a random value.
142  *
143  * @param mode desired quality of the random number
144  * @param i the upper limit (exclusive) for the random number
145  * @return a random value in the interval [0,i[.
146  */
147 uint32_t
148 GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i)
149 {
150 #ifdef gcry_fast_random_poll
151   static unsigned int invokeCount;
152 #endif
153   uint32_t ret;
154   uint32_t ul;
155
156   GNUNET_assert (i > 0);
157
158   switch (mode)
159   {
160   case GNUNET_CRYPTO_QUALITY_STRONG:
161     /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
162 #ifdef gcry_fast_random_poll
163     if ((invokeCount++ % 256) == 0)
164       gcry_fast_random_poll ();
165 #endif
166     ul = UINT32_MAX - (UINT32_MAX % i);
167     do
168     {
169       gcry_randomize ((unsigned char *) &ret, sizeof (uint32_t),
170                       GCRY_STRONG_RANDOM);
171     }
172     while (ret >= ul);
173     return ret % i;
174   case GNUNET_CRYPTO_QUALITY_NONCE:
175     ul = UINT32_MAX - (UINT32_MAX % i);
176     do
177     {
178       gcry_create_nonce (&ret, sizeof (ret));
179     }
180     while (ret >= ul);
181     return ret % i;
182   case GNUNET_CRYPTO_QUALITY_WEAK:
183     ret = i * get_weak_random ();
184     if (ret >= i)
185       ret = i - 1;
186     return ret;
187   default:
188     GNUNET_assert (0);
189   }
190   return 0;
191 }
192
193
194 /**
195  * Get an array with a random permutation of the
196  * numbers 0...n-1.
197  * @param mode GNUNET_RANDOM_QUALITY_STRONG if the strong (but expensive)
198  *        PRNG should be used, GNUNET_RANDOM_QUALITY_WEAK otherwise
199  * @param n the size of the array
200  * @return the permutation array (allocated from heap)
201  */
202 unsigned int *
203 GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n)
204 {
205   unsigned int *ret;
206   unsigned int i;
207   unsigned int tmp;
208   uint32_t x;
209
210   GNUNET_assert (n > 0);
211   ret = GNUNET_malloc (n * sizeof (unsigned int));
212   for (i = 0; i < n; i++)
213     ret[i] = i;
214   for (i = n - 1; i > 0; i--)
215   {
216     x = GNUNET_CRYPTO_random_u32 (mode, i + 1);
217     tmp = ret[x];
218     ret[x] = ret[i];
219     ret[i] = tmp;
220   }
221   return ret;
222 }
223
224 /**
225  * Random on unsigned 64-bit values.
226  *
227  *
228  * @param mode desired quality of the random number
229  * @param max value returned will be in range [0,max) (exclusive)
230  * @return random 64-bit number
231  */
232 uint64_t
233 GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max)
234 {
235   uint64_t ret;
236   uint64_t ul;
237
238   GNUNET_assert (max > 0);
239   switch (mode)
240   {
241   case GNUNET_CRYPTO_QUALITY_STRONG:
242     ul = UINT64_MAX - (UINT64_MAX % max);
243     do
244     {
245       gcry_randomize ((unsigned char *) &ret, sizeof (uint64_t),
246                       GCRY_STRONG_RANDOM);
247     }
248     while (ret >= ul);
249     return ret % max;
250   case GNUNET_CRYPTO_QUALITY_NONCE:
251     ul = UINT64_MAX - (UINT64_MAX % max);
252     do
253     {
254       gcry_create_nonce (&ret, sizeof (ret));
255     }
256     while (ret >= ul);
257
258     return ret % max;
259   case GNUNET_CRYPTO_QUALITY_WEAK:
260     ret = max * get_weak_random ();
261     if (ret >= max)
262       ret = max - 1;
263     return ret;
264   default:
265     GNUNET_assert (0);
266   }
267   return 0;
268 }
269
270
271 /**
272  * Process ID of the "find" process that we use for
273  * entropy gathering.
274  */
275 static struct GNUNET_OS_Process *genproc;
276
277
278 /**
279  * Function called by libgcrypt whenever we are
280  * blocked gathering entropy.
281  */
282 static void
283 entropy_generator (void *cls, const char *what, int printchar, int current,
284                    int total)
285 {
286   unsigned long code;
287   enum GNUNET_OS_ProcessStatusType type;
288   int ret;
289
290   if (0 != strcmp (what, "need_entropy"))
291     return;
292   if (current == total)
293   {
294     if (genproc != NULL)
295     {
296       if (0 != GNUNET_OS_process_kill (genproc, SIGKILL))
297         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "kill");
298       GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (genproc));
299       GNUNET_OS_process_destroy (genproc);
300       genproc = NULL;
301     }
302     return;
303   }
304   if (genproc != NULL)
305   {
306     ret = GNUNET_OS_process_status (genproc, &type, &code);
307     if (ret == GNUNET_NO)
308       return;                   /* still running */
309     if (ret == GNUNET_SYSERR)
310     {
311       GNUNET_break (0);
312       return;
313     }
314     if (0 != GNUNET_OS_process_kill (genproc, SIGKILL))
315       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "kill");
316     GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (genproc));
317     GNUNET_OS_process_destroy (genproc);
318     genproc = NULL;
319   }
320   LOG (GNUNET_ERROR_TYPE_INFO, _("Starting `%s' process to generate entropy\n"),
321        "find");
322   genproc =
323      GNUNET_OS_start_process (GNUNET_NO, 0,
324                               NULL, NULL, "sh", "sh", "-c",
325                               "exec find / -mount -type f -exec cp {} /dev/null \\; 2>/dev/null",
326                               NULL);
327 }
328
329
330 static void
331 killfind ()
332 {
333   if (genproc != NULL)
334   {
335     GNUNET_OS_process_kill (genproc, SIGKILL);
336     GNUNET_OS_process_destroy (genproc);
337     genproc = NULL;
338   }
339 }
340
341
342 void __attribute__ ((constructor))
343 GNUNET_CRYPTO_random_init ()
344 {
345   gcry_error_t rc;
346
347   if (! gcry_check_version (NEED_LIBGCRYPT_VERSION))
348   {
349     FPRINTF (stderr,
350              _
351              ("libgcrypt has not the expected version (version %s is required).\n"),
352              NEED_LIBGCRYPT_VERSION);
353     GNUNET_abort ();
354   }
355   if ((rc = gcry_control (GCRYCTL_DISABLE_SECMEM, 0)))
356     FPRINTF (stderr, "Failed to set libgcrypt option %s: %s\n", "DISABLE_SECMEM",
357              gcry_strerror (rc));
358   /* we only generate ephemeral keys in-process; for those,
359      we are fine with "just" using GCRY_STRONG_RANDOM */
360   if ((rc = gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0)))
361     FPRINTF (stderr,  "Failed to set libgcrypt option %s: %s\n", "ENABLE_QUICK_RANDOM",
362              gcry_strerror (rc));
363
364 #ifdef GCRYCTL_INITIALIZATION_FINISHED
365   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
366 #endif
367 #ifdef gcry_fast_random_poll
368   gcry_fast_random_poll ();
369 #endif
370   gcry_set_progress_handler (&entropy_generator, NULL);
371   atexit (&killfind);
372   GNUNET_CRYPTO_seed_weak_random (time (NULL) ^
373                                   GNUNET_CRYPTO_random_u32
374                                   (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
375 }
376
377
378 void __attribute__ ((destructor))
379 GNUNET_CRYPTO_random_fini ()
380 {
381   gcry_set_progress_handler (NULL, NULL);
382 }
383
384
385
386 /* end of crypto_random.c */