-fixes
[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 /**
100  * Produce a random value.
101  *
102  * @param mode desired quality of the random number
103  * @param i the upper limit (exclusive) for the random number
104  * @return a random value in the interval [0,i[.
105  */
106 uint32_t
107 GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i)
108 {
109 #ifdef gcry_fast_random_poll
110   static unsigned int invokeCount;
111 #endif
112   uint32_t ret;
113   uint32_t ul;
114
115   GNUNET_assert (i > 0);
116
117   switch (mode)
118   {
119   case GNUNET_CRYPTO_QUALITY_STRONG:
120     /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
121 #ifdef gcry_fast_random_poll
122     if ((invokeCount++ % 256) == 0)
123       gcry_fast_random_poll ();
124 #endif
125     ul = UINT32_MAX - (UINT32_MAX % i);
126     do
127     {
128       gcry_randomize ((unsigned char *) &ret, sizeof (uint32_t),
129                       GCRY_STRONG_RANDOM);
130     }
131     while (ret >= ul);
132     return ret % i;
133   case GNUNET_CRYPTO_QUALITY_NONCE:
134     ul = UINT32_MAX - (UINT32_MAX % i);
135     do
136     {
137       gcry_create_nonce (&ret, sizeof (ret));
138     }
139     while (ret >= ul);
140     return ret % i;
141   case GNUNET_CRYPTO_QUALITY_WEAK:
142     ret = i * get_weak_random ();
143     if (ret >= i)
144       ret = i - 1;
145     return ret;
146   default:
147     GNUNET_assert (0);
148   }
149   return 0;
150 }
151
152
153 /**
154  * Get an array with a random permutation of the
155  * numbers 0...n-1.
156  * @param mode GNUNET_RANDOM_QUALITY_STRONG if the strong (but expensive)
157  *        PRNG should be used, GNUNET_RANDOM_QUALITY_WEAK otherwise
158  * @param n the size of the array
159  * @return the permutation array (allocated from heap)
160  */
161 unsigned int *
162 GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n)
163 {
164   unsigned int *ret;
165   unsigned int i;
166   unsigned int tmp;
167   uint32_t x;
168
169   GNUNET_assert (n > 0);
170   ret = GNUNET_malloc (n * sizeof (unsigned int));
171   for (i = 0; i < n; i++)
172     ret[i] = i;
173   for (i = n - 1; i > 0; i--)
174   {
175     x = GNUNET_CRYPTO_random_u32 (mode, i + 1);
176     tmp = ret[x];
177     ret[x] = ret[i];
178     ret[i] = tmp;
179   }
180   return ret;
181 }
182
183 /**
184  * Random on unsigned 64-bit values.
185  *
186  *
187  * @param mode desired quality of the random number
188  * @param max value returned will be in range [0,max) (exclusive)
189  * @return random 64-bit number
190  */
191 uint64_t
192 GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max)
193 {
194   uint64_t ret;
195   uint64_t ul;
196
197   GNUNET_assert (max > 0);
198   switch (mode)
199   {
200   case GNUNET_CRYPTO_QUALITY_STRONG:
201     ul = UINT64_MAX - (UINT64_MAX % max);
202     do
203     {
204       gcry_randomize ((unsigned char *) &ret, sizeof (uint64_t),
205                       GCRY_STRONG_RANDOM);
206     }
207     while (ret >= ul);
208     return ret % max;
209   case GNUNET_CRYPTO_QUALITY_NONCE:
210     ul = UINT64_MAX - (UINT64_MAX % max);
211     do
212     {
213       gcry_create_nonce (&ret, sizeof (ret));
214     }
215     while (ret >= ul);
216
217     return ret % max;
218   case GNUNET_CRYPTO_QUALITY_WEAK:
219     ret = max * get_weak_random ();
220     if (ret >= max)
221       ret = max - 1;
222     return ret;
223   default:
224     GNUNET_assert (0);
225   }
226   return 0;
227 }
228
229
230 /**
231  * Process ID of the "find" process that we use for
232  * entropy gathering.
233  */
234 static struct GNUNET_OS_Process *genproc;
235
236
237 /**
238  * Function called by libgcrypt whenever we are
239  * blocked gathering entropy.
240  */
241 static void
242 entropy_generator (void *cls, const char *what, int printchar, int current,
243                    int total)
244 {
245   unsigned long code;
246   enum GNUNET_OS_ProcessStatusType type;
247   int ret;
248
249   if (0 != strcmp (what, "need_entropy"))
250     return;
251   if (current == total)
252   {
253     if (genproc != NULL)
254     {
255       if (0 != GNUNET_OS_process_kill (genproc, SIGKILL))
256         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "kill");
257       GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (genproc));
258       GNUNET_OS_process_destroy (genproc);
259       genproc = NULL;
260     }
261     return;
262   }
263   if (genproc != NULL)
264   {
265     ret = GNUNET_OS_process_status (genproc, &type, &code);
266     if (ret == GNUNET_NO)
267       return;                   /* still running */
268     if (ret == GNUNET_SYSERR)
269     {
270       GNUNET_break (0);
271       return;
272     }
273     if (0 != GNUNET_OS_process_kill (genproc, SIGKILL))
274       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "kill");
275     GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (genproc));
276     GNUNET_OS_process_destroy (genproc);
277     genproc = NULL;
278   }
279   LOG (GNUNET_ERROR_TYPE_INFO, _("Starting `%s' process to generate entropy\n"),
280        "find");
281   genproc =
282      GNUNET_OS_start_process (GNUNET_NO, 0,
283                               NULL, NULL, "sh", "sh", "-c",
284                               "exec find / -mount -type f -exec cp {} /dev/null \\; 2>/dev/null",
285                               NULL);
286 }
287
288
289 static void
290 killfind ()
291 {
292   if (genproc != NULL)
293   {
294     GNUNET_OS_process_kill (genproc, SIGKILL);
295     GNUNET_OS_process_destroy (genproc);
296     genproc = NULL;
297   }
298 }
299
300
301 void __attribute__ ((constructor))
302 GNUNET_CRYPTO_random_init ()
303 {
304   gcry_error_t rc;
305
306   if (! gcry_check_version (NEED_LIBGCRYPT_VERSION))
307   {
308     FPRINTF (stderr,
309              _
310              ("libgcrypt has not the expected version (version %s is required).\n"),
311              NEED_LIBGCRYPT_VERSION);
312     GNUNET_abort ();
313   }
314   if ((rc = gcry_control (GCRYCTL_DISABLE_SECMEM, 0)))
315     FPRINTF (stderr, "Failed to set libgcrypt option %s: %s\n", "DISABLE_SECMEM",
316              gcry_strerror (rc));
317   /* we only generate ephemeral keys in-process; for those,
318      we are fine with "just" using GCRY_STRONG_RANDOM */
319   if ((rc = gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0)))
320     FPRINTF (stderr,  "Failed to set libgcrypt option %s: %s\n", "ENABLE_QUICK_RANDOM",
321              gcry_strerror (rc));
322
323 #ifdef GCRYCTL_INITIALIZATION_FINISHED
324   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
325 #endif
326 #ifdef gcry_fast_random_poll
327   gcry_fast_random_poll ();
328 #endif
329   gcry_set_progress_handler (&entropy_generator, NULL);
330   atexit (&killfind);
331   GNUNET_CRYPTO_seed_weak_random (time (NULL) ^
332                                   GNUNET_CRYPTO_random_u32
333                                   (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
334 }
335
336
337 void __attribute__ ((destructor))
338 GNUNET_CRYPTO_random_fini ()
339 {
340   gcry_set_progress_handler (NULL, NULL);
341 }
342
343
344
345 /* end of crypto_random.c */