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