719acf07c6107e6e78b097f0eb16b76c4e247e47
[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 /**
38  * Create a cryptographically weak pseudo-random number in the interval of 0 to 1.
39  *
40  * @return number between 0 and 1.
41  */
42 static double
43 weak_random ()
44 {
45   return ((double) RANDOM () / RAND_MAX);
46 }
47
48
49 /**
50  * Produce a random value.
51  *
52  * @param mode desired quality of the random number
53  * @param i the upper limit (exclusive) for the random number
54  * @return a random value in the interval [0,i[.
55  */
56 uint32_t
57 GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i)
58 {
59 #ifdef gcry_fast_random_poll
60   static unsigned int invokeCount;
61 #endif
62   uint32_t ret;
63   uint32_t ul;
64
65   GNUNET_assert (i > 0);
66
67   switch (mode)
68   {
69   case GNUNET_CRYPTO_QUALITY_STRONG:
70     /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
71 #ifdef gcry_fast_random_poll
72     if ((invokeCount++ % 256) == 0)
73       gcry_fast_random_poll ();
74 #endif
75     ul = UINT32_MAX - (UINT32_MAX % i);
76     do
77     {
78       gcry_randomize ((unsigned char *) &ret, sizeof (uint32_t),
79                       GCRY_STRONG_RANDOM);
80     }
81     while (ret >= ul);
82     return ret % i;
83   case GNUNET_CRYPTO_QUALITY_NONCE:
84     ul = UINT32_MAX - (UINT32_MAX % i);
85     do
86     {
87       gcry_create_nonce (&ret, sizeof (ret));
88     }
89     while (ret >= ul);
90     return ret % i;
91   case GNUNET_CRYPTO_QUALITY_WEAK:
92     ret = i * weak_random ();
93     if (ret >= i)
94       ret = i - 1;
95     return ret;
96   default:
97     GNUNET_assert (0);
98   }
99   return 0;
100 }
101
102
103 /**
104  * Get an array with a random permutation of the
105  * numbers 0...n-1.
106  * @param mode GNUNET_RANDOM_QUALITY_STRONG if the strong (but expensive)
107  *        PRNG should be used, GNUNET_RANDOM_QUALITY_WEAK otherwise
108  * @param n the size of the array
109  * @return the permutation array (allocated from heap)
110  */
111 unsigned int *
112 GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n)
113 {
114   unsigned int *ret;
115   unsigned int i;
116   unsigned int tmp;
117   uint32_t x;
118
119   GNUNET_assert (n > 0);
120   ret = GNUNET_malloc (n * sizeof (unsigned int));
121   for (i = 0; i < n; i++)
122     ret[i] = i;
123   for (i = n - 1; i > 0; i--)
124   {
125     x = GNUNET_CRYPTO_random_u32 (mode, i + 1);
126     tmp = ret[x];
127     ret[x] = ret[i];
128     ret[i] = tmp;
129   }
130   return ret;
131 }
132
133 /**
134  * Random on unsigned 64-bit values.
135  *
136  *
137  * @param mode desired quality of the random number
138  * @param max value returned will be in range [0,max) (exclusive)
139  * @return random 64-bit number
140  */
141 uint64_t
142 GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max)
143 {
144   uint64_t ret;
145   uint64_t ul;
146
147   GNUNET_assert (max > 0);
148   switch (mode)
149   {
150   case GNUNET_CRYPTO_QUALITY_STRONG:
151     ul = UINT64_MAX - (UINT64_MAX % max);
152     do
153     {
154       gcry_randomize ((unsigned char *) &ret, sizeof (uint64_t),
155                       GCRY_STRONG_RANDOM);
156     }
157     while (ret >= ul);
158     return ret % max;
159   case GNUNET_CRYPTO_QUALITY_NONCE:
160     ul = UINT64_MAX - (UINT64_MAX % max);
161     do
162     {
163       gcry_create_nonce (&ret, sizeof (ret));
164     }
165     while (ret >= ul);
166
167     return ret % max;
168   case GNUNET_CRYPTO_QUALITY_WEAK:
169     ret = max * weak_random ();
170     if (ret >= max)
171       ret = max - 1;
172     return ret;
173   default:
174     GNUNET_assert (0);
175   }
176   return 0;
177 }
178
179 /**
180  * This function should only be called in testcases
181  * where strong entropy gathering is not desired
182  * (for example, for hostkey generation).
183  */
184 void
185 GNUNET_CRYPTO_random_disable_entropy_gathering ()
186 {
187   gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
188 }
189
190
191 /**
192  * Process ID of the "find" process that we use for
193  * entropy gathering.
194  */
195 static struct GNUNET_OS_Process *genproc;
196
197 /**
198  * Function called by libgcrypt whenever we are
199  * blocked gathering entropy.
200  */
201 static void
202 entropy_generator (void *cls, const char *what, int printchar, int current,
203                    int total)
204 {
205   unsigned long code;
206   enum GNUNET_OS_ProcessStatusType type;
207   int ret;
208
209   if (0 != strcmp (what, "need_entropy"))
210     return;
211   if (current == total)
212   {
213     if (genproc != NULL)
214     {
215       if (0 != GNUNET_OS_process_kill (genproc, SIGTERM))
216         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "kill");
217       GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (genproc));
218       GNUNET_OS_process_close (genproc);
219       genproc = NULL;
220     }
221     return;
222   }
223   if (genproc != NULL)
224   {
225     ret = GNUNET_OS_process_status (genproc, &type, &code);
226     if (ret == GNUNET_NO)
227       return;                   /* still running */
228     if (ret == GNUNET_SYSERR)
229     {
230       GNUNET_break (0);
231       return;
232     }
233     if (0 != GNUNET_OS_process_kill (genproc, SIGTERM))
234       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "kill");
235     GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (genproc));
236     GNUNET_OS_process_close (genproc);
237     genproc = NULL;
238   }
239   LOG (GNUNET_ERROR_TYPE_INFO, _("Starting `%s' process to generate entropy\n"),
240        "find");
241   genproc =
242       GNUNET_OS_start_process (NULL, NULL, "sh", "sh", "-c",
243                                "exec find / -mount -type f -exec cp {} /dev/null \\; 2>/dev/null",
244                                NULL);
245 }
246
247
248 static void
249 killfind ()
250 {
251   if (genproc != NULL)
252   {
253     GNUNET_OS_process_kill (genproc, SIGKILL);
254     GNUNET_OS_process_close (genproc);
255     genproc = NULL;
256   }
257 }
258
259
260 void __attribute__ ((constructor)) GNUNET_CRYPTO_random_init ()
261 {
262   gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
263   if (!gcry_check_version (GCRYPT_VERSION))
264   {
265     fprintf (stderr,
266              _
267              ("libgcrypt has not the expected version (version %s is required).\n"),
268              GCRYPT_VERSION);
269     GNUNET_abort ();
270   }
271 #ifdef gcry_fast_random_poll
272   gcry_fast_random_poll ();
273 #endif
274   gcry_set_progress_handler (&entropy_generator, NULL);
275   atexit (&killfind);
276   SRANDOM (time (NULL) ^
277            GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
278 }
279
280
281 void __attribute__ ((destructor)) GNUNET_CRYPTO_random_fini ()
282 {
283   gcry_set_progress_handler (NULL, NULL);
284 }
285
286
287
288 /* end of crypto_random.c */