src/util: Use make 4.0 assignment operator
[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  * Fill block with a random values.
102  *
103  * @param mode desired quality of the random number
104  * @param buffer the buffer to fill
105  * @param length buffer length
106  */
107 void
108 GNUNET_CRYPTO_random_block (enum GNUNET_CRYPTO_Quality mode, void *buffer, size_t length)
109 {
110 #ifdef gcry_fast_random_poll
111   static unsigned int invokeCount;
112 #endif
113   switch (mode)
114   {
115   case GNUNET_CRYPTO_QUALITY_STRONG:
116     /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
117 #ifdef gcry_fast_random_poll
118     if ((invokeCount++ % 256) == 0)
119       gcry_fast_random_poll ();
120 #endif
121     gcry_randomize (buffer, length, GCRY_STRONG_RANDOM);
122     return;
123   case GNUNET_CRYPTO_QUALITY_NONCE:
124     gcry_create_nonce (buffer, length);
125     return;
126   case GNUNET_CRYPTO_QUALITY_WEAK:
127     /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
128 #ifdef gcry_fast_random_poll
129     if ((invokeCount++ % 256) == 0)
130       gcry_fast_random_poll ();
131 #endif
132     gcry_randomize (buffer, length, GCRY_WEAK_RANDOM);
133     return;
134   default:
135     GNUNET_assert (0);
136   }
137 }
138
139
140 /**
141  * Produce a random unsigned 32-bit number modulo @a i.
142  *
143  * @param mode desired quality of the random number
144  * @param i the upper limit (exclusive) for the random number
145  * @return a random value in the interval [0,i[.
146  */
147 uint32_t
148 GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode,
149                           uint32_t i)
150 {
151 #ifdef gcry_fast_random_poll
152   static unsigned int invokeCount;
153 #endif
154   uint32_t ret;
155   uint32_t ul;
156
157   GNUNET_assert (i > 0);
158
159   switch (mode)
160   {
161   case GNUNET_CRYPTO_QUALITY_STRONG:
162     /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
163 #ifdef gcry_fast_random_poll
164     if ((invokeCount++ % 256) == 0)
165       gcry_fast_random_poll ();
166 #endif
167     ul = UINT32_MAX - (UINT32_MAX % i);
168     do
169     {
170       gcry_randomize ((unsigned char *) &ret, sizeof (uint32_t),
171                       GCRY_STRONG_RANDOM);
172     }
173     while (ret >= ul);
174     return ret % i;
175   case GNUNET_CRYPTO_QUALITY_NONCE:
176     ul = UINT32_MAX - (UINT32_MAX % i);
177     do
178     {
179       gcry_create_nonce (&ret, sizeof (ret));
180     }
181     while (ret >= ul);
182     return ret % i;
183   case GNUNET_CRYPTO_QUALITY_WEAK:
184     ret = i * get_weak_random ();
185     if (ret >= i)
186       ret = i - 1;
187     return ret;
188   default:
189     GNUNET_assert (0);
190   }
191   return 0;
192 }
193
194
195 /**
196  * Get an array with a random permutation of the
197  * numbers 0...n-1.
198  * @param mode #GNUNET_RANDOM_QUALITY_STRONG if the strong (but expensive)
199  *        PRNG should be used, #GNUNET_RANDOM_QUALITY_WEAK otherwise
200  * @param n the size of the array
201  * @return the permutation array (allocated from heap)
202  */
203 unsigned int *
204 GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode,
205                               unsigned int n)
206 {
207   unsigned int *ret;
208   unsigned int i;
209   unsigned int tmp;
210   uint32_t x;
211
212   GNUNET_assert (n > 0);
213   ret = GNUNET_malloc (n * sizeof (unsigned int));
214   for (i = 0; i < n; i++)
215     ret[i] = i;
216   for (i = n - 1; i > 0; i--)
217   {
218     x = GNUNET_CRYPTO_random_u32 (mode, i + 1);
219     tmp = ret[x];
220     ret[x] = ret[i];
221     ret[i] = tmp;
222   }
223   return ret;
224 }
225
226
227 /**
228  * Generate random unsigned 64-bit value.
229  *
230  * @param mode desired quality of the random number
231  * @param max value returned will be in range [0,max) (exclusive)
232  * @return random 64-bit number
233  */
234 uint64_t
235 GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max)
236 {
237   uint64_t ret;
238   uint64_t ul;
239
240   GNUNET_assert (max > 0);
241   switch (mode)
242   {
243   case GNUNET_CRYPTO_QUALITY_STRONG:
244     ul = UINT64_MAX - (UINT64_MAX % max);
245     do
246     {
247       gcry_randomize ((unsigned char *) &ret, sizeof (uint64_t),
248                       GCRY_STRONG_RANDOM);
249     }
250     while (ret >= ul);
251     return ret % max;
252   case GNUNET_CRYPTO_QUALITY_NONCE:
253     ul = UINT64_MAX - (UINT64_MAX % max);
254     do
255     {
256       gcry_create_nonce (&ret, sizeof (ret));
257     }
258     while (ret >= ul);
259
260     return ret % max;
261   case GNUNET_CRYPTO_QUALITY_WEAK:
262     ret = max * get_weak_random ();
263     if (ret >= max)
264       ret = max - 1;
265     return ret;
266   default:
267     GNUNET_assert (0);
268   }
269   return 0;
270 }
271
272
273 /**
274  * Allocation wrapper for libgcrypt, used to avoid bad locking
275  * strategy of libgcrypt implementation.
276  */
277 static void *
278 w_malloc (size_t n)
279 {
280   return calloc (n, 1);
281 }
282
283
284 /**
285  * Allocation wrapper for libgcrypt, used to avoid bad locking
286  * strategy of libgcrypt implementation.
287  */
288 static int
289 w_check (const void *p)
290 {
291   return 0; /* not secure memory */
292 }
293
294
295 /**
296  * Initialize libgcrypt.
297  */
298 void __attribute__ ((constructor))
299 GNUNET_CRYPTO_random_init ()
300 {
301   gcry_error_t rc;
302
303   if (! gcry_check_version (NEED_LIBGCRYPT_VERSION))
304   {
305     FPRINTF (stderr,
306              _("libgcrypt has not the expected version (version %s is required).\n"),
307              NEED_LIBGCRYPT_VERSION);
308     GNUNET_assert (0);
309   }
310   /* set custom allocators */
311   gcry_set_allocation_handler (&w_malloc,
312                                &w_malloc,
313                                &w_check,
314                                &realloc,
315                                &free);
316   /* Disable use of secure memory */
317   if ((rc = gcry_control (GCRYCTL_DISABLE_SECMEM, 0)))
318     FPRINTF (stderr,
319              "Failed to set libgcrypt option %s: %s\n",
320              "DISABLE_SECMEM",
321              gcry_strerror (rc));
322   /* Otherwise gnunet-ecc takes forever to complete, besides
323      we are fine with "just" using GCRY_STRONG_RANDOM */
324   if ((rc = gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0)))
325     FPRINTF (stderr,
326              "Failed to set libgcrypt option %s: %s\n",
327              "ENABLE_QUICK_RANDOM",
328              gcry_strerror (rc));
329   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
330   gcry_fast_random_poll ();
331   GNUNET_CRYPTO_seed_weak_random (time (NULL) ^
332                                   GNUNET_CRYPTO_random_u32
333                                   (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
334 }
335
336
337 /**
338  * Nicely shut down libgcrypt.
339  */
340 void __attribute__ ((destructor))
341 GNUNET_CRYPTO_random_fini ()
342 {
343   gcry_set_progress_handler (NULL, NULL);
344 #ifdef GCRYCTL_CLOSE_RANDOM_DEVICE
345   (void) gcry_control (GCRYCTL_CLOSE_RANDOM_DEVICE, 0);
346 #endif
347 }
348
349
350
351 /* end of crypto_random.c */