tolerate additional IPv4 address now available for gnunet.org
[oweals/gnunet.git] / src / util / crypto_random.c
1 /*
2      This file is part of GNUnet.  Copyright (C) 2001-2014 Christian Grothoff
3      (and other contributing authors)
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
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_crypto_lib.h"
29 #include <gcrypt.h>
30
31 #define LOG(kind,...) GNUNET_log_from (kind, "util-crypto-random", __VA_ARGS__)
32
33 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-crypto-random", 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  * @ingroup crypto
101  * Zero out @a buffer, securely against compiler optimizations.
102  * Used to delete key material.
103  *
104  * @param buffer the buffer to zap
105  * @param length buffer length
106  */
107 void
108 GNUNET_CRYPTO_zero_keys (void *buffer,
109                          size_t length)
110 {
111 #if HAVE_MEMSET_S
112   memset_s (buffer,
113             length,
114             0,
115             length);
116 #elif HAVE_EXPLICIT_BZERO
117   explicit_bzero (buffer,
118                   length);
119 #else
120   volatile unsigned char *p = buffer;
121   while (length--)
122     *p++ = 0;
123 #endif
124 }
125
126
127 /**
128  * @ingroup crypto
129  * Fill block with a random values.
130  *
131  * @param mode desired quality of the random number
132  * @param buffer the buffer to fill
133  * @param length buffer length
134  */
135 void
136 GNUNET_CRYPTO_random_block (enum GNUNET_CRYPTO_Quality mode,
137                             void *buffer,
138                             size_t length)
139 {
140 #ifdef gcry_fast_random_poll
141   static unsigned int invokeCount;
142 #endif
143   switch (mode)
144   {
145   case GNUNET_CRYPTO_QUALITY_STRONG:
146     /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
147 #ifdef gcry_fast_random_poll
148     if ((invokeCount++ % 256) == 0)
149       gcry_fast_random_poll ();
150 #endif
151     gcry_randomize (buffer, length, GCRY_STRONG_RANDOM);
152     return;
153   case GNUNET_CRYPTO_QUALITY_NONCE:
154     gcry_create_nonce (buffer, length);
155     return;
156   case GNUNET_CRYPTO_QUALITY_WEAK:
157     /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
158 #ifdef gcry_fast_random_poll
159     if ((invokeCount++ % 256) == 0)
160       gcry_fast_random_poll ();
161 #endif
162     gcry_randomize (buffer, length, GCRY_WEAK_RANDOM);
163     return;
164   default:
165     GNUNET_assert (0);
166   }
167 }
168
169
170 /**
171  * Produce a random unsigned 32-bit number modulo @a i.
172  *
173  * @param mode desired quality of the random number
174  * @param i the upper limit (exclusive) for the random number
175  * @return a random value in the interval [0,i[.
176  */
177 uint32_t
178 GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode,
179                           uint32_t i)
180 {
181 #ifdef gcry_fast_random_poll
182   static unsigned int invokeCount;
183 #endif
184   uint32_t ret;
185   uint32_t ul;
186
187   GNUNET_assert (i > 0);
188
189   switch (mode)
190   {
191   case GNUNET_CRYPTO_QUALITY_STRONG:
192     /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
193 #ifdef gcry_fast_random_poll
194     if ((invokeCount++ % 256) == 0)
195       gcry_fast_random_poll ();
196 #endif
197     ul = UINT32_MAX - (UINT32_MAX % i);
198     do
199     {
200       gcry_randomize ((unsigned char *) &ret, sizeof (uint32_t),
201                       GCRY_STRONG_RANDOM);
202     }
203     while (ret >= ul);
204     return ret % i;
205   case GNUNET_CRYPTO_QUALITY_NONCE:
206     ul = UINT32_MAX - (UINT32_MAX % i);
207     do
208     {
209       gcry_create_nonce (&ret, sizeof (ret));
210     }
211     while (ret >= ul);
212     return ret % i;
213   case GNUNET_CRYPTO_QUALITY_WEAK:
214     ret = i * get_weak_random ();
215     if (ret >= i)
216       ret = i - 1;
217     return ret;
218   default:
219     GNUNET_assert (0);
220   }
221   return 0;
222 }
223
224
225 /**
226  * Get an array with a random permutation of the
227  * numbers 0...n-1.
228  * @param mode #GNUNET_RANDOM_QUALITY_STRONG if the strong (but expensive)
229  *        PRNG should be used, #GNUNET_RANDOM_QUALITY_WEAK otherwise
230  * @param n the size of the array
231  * @return the permutation array (allocated from heap)
232  */
233 unsigned int *
234 GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode,
235                               unsigned int n)
236 {
237   unsigned int *ret;
238   unsigned int i;
239   unsigned int tmp;
240   uint32_t x;
241
242   GNUNET_assert (n > 0);
243   ret = GNUNET_malloc (n * sizeof (unsigned int));
244   for (i = 0; i < n; i++)
245     ret[i] = i;
246   for (i = n - 1; i > 0; i--)
247   {
248     x = GNUNET_CRYPTO_random_u32 (mode, i + 1);
249     tmp = ret[x];
250     ret[x] = ret[i];
251     ret[i] = tmp;
252   }
253   return ret;
254 }
255
256
257 /**
258  * Generate random unsigned 64-bit value.
259  *
260  * @param mode desired quality of the random number
261  * @param max value returned will be in range [0,max) (exclusive)
262  * @return random 64-bit number
263  */
264 uint64_t
265 GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode,
266                           uint64_t max)
267 {
268   uint64_t ret;
269   uint64_t ul;
270
271   GNUNET_assert (max > 0);
272   switch (mode)
273   {
274   case GNUNET_CRYPTO_QUALITY_STRONG:
275     ul = UINT64_MAX - (UINT64_MAX % max);
276     do
277     {
278       gcry_randomize ((unsigned char *) &ret, sizeof (uint64_t),
279                       GCRY_STRONG_RANDOM);
280     }
281     while (ret >= ul);
282     return ret % max;
283   case GNUNET_CRYPTO_QUALITY_NONCE:
284     ul = UINT64_MAX - (UINT64_MAX % max);
285     do
286     {
287       gcry_create_nonce (&ret, sizeof (ret));
288     }
289     while (ret >= ul);
290
291     return ret % max;
292   case GNUNET_CRYPTO_QUALITY_WEAK:
293     ret = max * get_weak_random ();
294     if (ret >= max)
295       ret = max - 1;
296     return ret;
297   default:
298     GNUNET_assert (0);
299   }
300   return 0;
301 }
302
303
304 /**
305  * Allocation wrapper for libgcrypt, used to avoid bad locking
306  * strategy of libgcrypt implementation.
307  */
308 static void *
309 w_malloc (size_t n)
310 {
311   return calloc (n, 1);
312 }
313
314
315 /**
316  * Allocation wrapper for libgcrypt, used to avoid bad locking
317  * strategy of libgcrypt implementation.
318  */
319 static int
320 w_check (const void *p)
321 {
322   return 0; /* not secure memory */
323 }
324
325
326 /**
327  * Initialize libgcrypt.
328  */
329 void __attribute__ ((constructor))
330 GNUNET_CRYPTO_random_init ()
331 {
332   gcry_error_t rc;
333
334   if (! gcry_check_version (NEED_LIBGCRYPT_VERSION))
335   {
336     FPRINTF (stderr,
337              _("libgcrypt has not the expected version (version %s is required).\n"),
338              NEED_LIBGCRYPT_VERSION);
339     GNUNET_assert (0);
340   }
341   /* set custom allocators */
342   gcry_set_allocation_handler (&w_malloc,
343                                &w_malloc,
344                                &w_check,
345                                &realloc,
346                                &free);
347   /* Disable use of secure memory */
348   if ((rc = gcry_control (GCRYCTL_DISABLE_SECMEM, 0)))
349     FPRINTF (stderr,
350              "Failed to set libgcrypt option %s: %s\n",
351              "DISABLE_SECMEM",
352              gcry_strerror (rc));
353   /* Otherwise gnunet-ecc takes forever to complete, besides
354      we are fine with "just" using GCRY_STRONG_RANDOM */
355   if ((rc = gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0)))
356     FPRINTF (stderr,
357              "Failed to set libgcrypt option %s: %s\n",
358              "ENABLE_QUICK_RANDOM",
359              gcry_strerror (rc));
360   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
361   gcry_fast_random_poll ();
362   GNUNET_CRYPTO_seed_weak_random (time (NULL) ^
363                                   GNUNET_CRYPTO_random_u32
364                                   (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
365 }
366
367
368 /**
369  * Nicely shut down libgcrypt.
370  */
371 void __attribute__ ((destructor))
372 GNUNET_CRYPTO_random_fini ()
373 {
374   gcry_set_progress_handler (NULL, NULL);
375 #ifdef GCRYCTL_CLOSE_RANDOM_DEVICE
376   (void) gcry_control (GCRYCTL_CLOSE_RANDOM_DEVICE, 0);
377 #endif
378 }
379
380
381
382 /* end of crypto_random.c */