LRN: Fix the use of SRANDOM
[oweals/gnunet.git] / src / util / crypto_random.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2003, 2004, 2005, 2006 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 2, 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_common.h"
29 #include "gnunet_crypto_lib.h"
30 #include "gnunet_os_lib.h"
31 #include <gcrypt.h>
32
33 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
34
35 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
36
37 /* TODO: ndurner, move this to plibc? */
38 /* The code is derived from glibc, obviously */
39 #if MINGW
40 #ifdef RANDOM
41 #  undef RANDOM
42 #endif
43 #ifdef SRANDOM
44 #  undef SRANDOM
45 #endif
46 #define RANDOM() glibc_weak_rand32()
47 #define SRANDOM(s) glibc_weak_srand32(s)
48 static int32_t glibc_weak_rand32_state = 1;
49
50 void
51 glibc_weak_srand32 (int32_t s)
52 {
53   glibc_weak_rand32_state = s;
54 }
55
56 int32_t
57 glibc_weak_rand32 ()
58 {
59   int32_t val = glibc_weak_rand32_state;
60   val = ((glibc_weak_rand32_state * 1103515245) + 12345) & 0x7fffffff;
61   glibc_weak_rand32_state = val;
62   return val;
63 }
64 #endif
65
66 /**
67  * Create a cryptographically weak pseudo-random number in the interval of 0 to 1.
68  *
69  * @return number between 0 and 1.
70  */
71 static double
72 weak_random ()
73 {
74   return ((double) RANDOM () / RAND_MAX);
75 }
76
77 /**
78  * Seed a weak random generator. Only GNUNET_CRYPTO_QUALITY_WEAK-mode generator
79  * can be seeded.
80  *
81  * @param seed the seed to use
82  */
83 void
84 GNUNET_CRYPTO_seed_weak_random (int32_t seed)
85 {
86   SRANDOM (seed);
87 }
88
89 /**
90  * Produce a random value.
91  *
92  * @param mode desired quality of the random number
93  * @param i the upper limit (exclusive) for the random number
94  * @return a random value in the interval [0,i[.
95  */
96 uint32_t
97 GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i)
98 {
99 #ifdef gcry_fast_random_poll
100   static unsigned int invokeCount;
101 #endif
102   uint32_t ret;
103   uint32_t ul;
104
105   GNUNET_assert (i > 0);
106
107   switch (mode)
108   {
109   case GNUNET_CRYPTO_QUALITY_STRONG:
110     /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
111 #ifdef gcry_fast_random_poll
112     if ((invokeCount++ % 256) == 0)
113       gcry_fast_random_poll ();
114 #endif
115     ul = UINT32_MAX - (UINT32_MAX % i);
116     do
117     {
118       gcry_randomize ((unsigned char *) &ret, sizeof (uint32_t),
119                       GCRY_STRONG_RANDOM);
120     }
121     while (ret >= ul);
122     return ret % i;
123   case GNUNET_CRYPTO_QUALITY_NONCE:
124     ul = UINT32_MAX - (UINT32_MAX % i);
125     do
126     {
127       gcry_create_nonce (&ret, sizeof (ret));
128     }
129     while (ret >= ul);
130     return ret % i;
131   case GNUNET_CRYPTO_QUALITY_WEAK:
132     ret = i * weak_random ();
133     if (ret >= i)
134       ret = i - 1;
135     return ret;
136   default:
137     GNUNET_assert (0);
138   }
139   return 0;
140 }
141
142
143 /**
144  * Get an array with a random permutation of the
145  * numbers 0...n-1.
146  * @param mode GNUNET_RANDOM_QUALITY_STRONG if the strong (but expensive)
147  *        PRNG should be used, GNUNET_RANDOM_QUALITY_WEAK otherwise
148  * @param n the size of the array
149  * @return the permutation array (allocated from heap)
150  */
151 unsigned int *
152 GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n)
153 {
154   unsigned int *ret;
155   unsigned int i;
156   unsigned int tmp;
157   uint32_t x;
158
159   GNUNET_assert (n > 0);
160   ret = GNUNET_malloc (n * sizeof (unsigned int));
161   for (i = 0; i < n; i++)
162     ret[i] = i;
163   for (i = n - 1; i > 0; i--)
164   {
165     x = GNUNET_CRYPTO_random_u32 (mode, i + 1);
166     tmp = ret[x];
167     ret[x] = ret[i];
168     ret[i] = tmp;
169   }
170   return ret;
171 }
172
173 /**
174  * Random on unsigned 64-bit values.
175  *
176  *
177  * @param mode desired quality of the random number
178  * @param max value returned will be in range [0,max) (exclusive)
179  * @return random 64-bit number
180  */
181 uint64_t
182 GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max)
183 {
184   uint64_t ret;
185   uint64_t ul;
186
187   GNUNET_assert (max > 0);
188   switch (mode)
189   {
190   case GNUNET_CRYPTO_QUALITY_STRONG:
191     ul = UINT64_MAX - (UINT64_MAX % max);
192     do
193     {
194       gcry_randomize ((unsigned char *) &ret, sizeof (uint64_t),
195                       GCRY_STRONG_RANDOM);
196     }
197     while (ret >= ul);
198     return ret % max;
199   case GNUNET_CRYPTO_QUALITY_NONCE:
200     ul = UINT64_MAX - (UINT64_MAX % max);
201     do
202     {
203       gcry_create_nonce (&ret, sizeof (ret));
204     }
205     while (ret >= ul);
206
207     return ret % max;
208   case GNUNET_CRYPTO_QUALITY_WEAK:
209     ret = max * weak_random ();
210     if (ret >= max)
211       ret = max - 1;
212     return ret;
213   default:
214     GNUNET_assert (0);
215   }
216   return 0;
217 }
218
219 /**
220  * This function should only be called in testcases
221  * where strong entropy gathering is not desired
222  * (for example, for hostkey generation).
223  */
224 void
225 GNUNET_CRYPTO_random_disable_entropy_gathering ()
226 {
227   gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
228 }
229
230
231 /**
232  * Process ID of the "find" process that we use for
233  * entropy gathering.
234  */
235 static struct GNUNET_OS_Process *genproc;
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, SIGTERM))
256         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "kill");
257       GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (genproc));
258       GNUNET_OS_process_close (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, SIGTERM))
274       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "kill");
275     GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (genproc));
276     GNUNET_OS_process_close (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 (NULL, NULL, "sh", "sh", "-c",
283                                "exec find / -mount -type f -exec cp {} /dev/null \\; 2>/dev/null",
284                                NULL);
285 }
286
287
288 static void
289 killfind ()
290 {
291   if (genproc != NULL)
292   {
293     GNUNET_OS_process_kill (genproc, SIGKILL);
294     GNUNET_OS_process_close (genproc);
295     genproc = NULL;
296   }
297 }
298
299
300 void __attribute__ ((constructor)) GNUNET_CRYPTO_random_init ()
301 {
302   gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
303   if (!gcry_check_version (GCRYPT_VERSION))
304   {
305     fprintf (stderr,
306              _
307              ("libgcrypt has not the expected version (version %s is required).\n"),
308              GCRYPT_VERSION);
309     GNUNET_abort ();
310   }
311 #ifdef gcry_fast_random_poll
312   gcry_fast_random_poll ();
313 #endif
314   gcry_set_progress_handler (&entropy_generator, NULL);
315   atexit (&killfind);
316   GNUNET_CRYPTO_seed_weak_random (time (NULL) ^
317       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
318 }
319
320
321 void __attribute__ ((destructor)) GNUNET_CRYPTO_random_fini ()
322 {
323   gcry_set_progress_handler (NULL, NULL);
324 }
325
326
327
328 /* end of crypto_random.c */