5 * Mark Crichton (crichton@gimp.org)
6 * Patrik Torstensson (p@rxc.se)
7 * Sebastien Pouliot (sebastien@ximian.com)
8 * Ludovic Henry (ludovic.henry@xamarin.com)
10 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
11 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12 * Copyright 2001 Xamarin, Inc (http://www.novell.com)
20 #include "mono-rand.h"
21 #include "mono-threads.h"
22 #include "metadata/exception.h"
23 #include "metadata/object.h"
30 #ifndef PROV_INTEL_SEC
31 #define PROV_INTEL_SEC 22
33 #ifndef CRYPT_VERIFY_CONTEXT
34 #define CRYPT_VERIFY_CONTEXT 0xF0000000
40 * Returns: True if random source is global, false if mono_rand_init can be called repeatedly to get randomness instances.
42 * Initializes entire RNG system. Must be called once per process before calling mono_rand_init.
52 * @seed: A string containing seed data
53 * @seed_size: Length of seed string
55 * Returns: On success, a non-NULL handle which can be used to fetch random data from mono_rand_try_get_bytes. On failure, NULL.
57 * Initializes an RNG client.
60 mono_rand_init (guchar *seed, gint seed_size)
62 HCRYPTPROV provider = 0;
64 /* There is no need to create a container for just random data,
65 * so we can use CRYPT_VERIFY_CONTEXT (one call) see:
66 * http://blogs.msdn.com/dangriff/archive/2003/11/19/51709.aspx */
68 /* We first try to use the Intel PIII RNG if drivers are present */
69 if (!CryptAcquireContext (&provider, NULL, NULL, PROV_INTEL_SEC, CRYPT_VERIFY_CONTEXT)) {
70 /* not a PIII or no drivers available, use default RSA CSP */
71 if (!CryptAcquireContext (&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFY_CONTEXT)) {
72 /* exception will be thrown in managed code */
77 /* seed the CSP with the supplied buffer (if present) */
78 if (provider != 0 && seed) {
79 /* the call we replace the seed with random - this isn't what is
80 * expected from the class library user */
81 guchar *data = g_malloc (seed_size);
83 memcpy (data, seed, seed_size);
84 /* add seeding material to the RNG */
85 CryptGenRandom (provider, seed_size, data);
86 /* zeroize and free */
87 memset (data, 0, seed_size);
92 return (gpointer) provider;
96 * mono_rand_try_get_bytes:
97 * @handle: A pointer to an RNG handle. Handle is set to NULL on failure.
98 * @buffer: A buffer into which to write random data.
99 * @buffer_size: Number of bytes to write into buffer.
101 * Returns: FALSE on failure, TRUE on success.
103 * Extracts bytes from an RNG handle.
106 mono_rand_try_get_bytes (gpointer *handle, guchar *buffer, gint buffer_size)
111 provider = (HCRYPTPROV) *handle;
113 if (!CryptGenRandom (provider, buffer_size, buffer)) {
114 CryptReleaseContext (provider, 0);
115 /* we may have lost our context with CryptoAPI, but all hope isn't lost yet! */
116 provider = (HCRYPTPROV) mono_rand_init (NULL, 0);
117 if (!CryptGenRandom (provider, buffer_size, buffer)) {
118 /* exception will be thrown in managed code */
119 CryptReleaseContext (provider, 0);
129 * @handle: An RNG handle.
130 * @buffer: A buffer into which to write random data.
131 * @buffer_size: Number of bytes to write into buffer.
133 * Releases an RNG handle.
136 mono_rand_close (gpointer handle)
138 CryptReleaseContext ((HCRYPTPROV) handle, 0);
141 #elif defined (HAVE_SYS_UN_H) && !defined(__native_client__)
146 #include <sys/socket.h>
147 #include <sys/types.h>
150 #ifndef NAME_DEV_URANDOM
151 #define NAME_DEV_URANDOM "/dev/urandom"
154 static gboolean use_egd = FALSE;
155 static gint file = -1;
158 get_entropy_from_egd (const char *path, guchar *buffer, int buffer_size)
160 struct sockaddr_un egd_addr;
165 file = socket (PF_UNIX, SOCK_STREAM, 0);
169 egd_addr.sun_family = AF_UNIX;
170 strncpy (egd_addr.sun_path, path, sizeof (egd_addr.sun_path) - 1);
171 egd_addr.sun_path [sizeof (egd_addr.sun_path) - 1] = '\0';
172 ret = connect (file, (struct sockaddr*) &egd_addr, sizeof (egd_addr));
177 g_warning ("Entropy problem! Can't create or connect to egd socket %s", path);
178 mono_raise_exception (mono_get_exception_execution_engine ("Failed to open egd socket"));
181 while (buffer_size > 0) {
185 /* block until daemon can return enough entropy */
187 request [1] = buffer_size < 255 ? buffer_size : 255;
189 int sent = write (file, request + count, 2 - count);
192 } else if (errno == EINTR) {
196 g_warning ("Send egd request failed %d", errno);
197 mono_raise_exception (mono_get_exception_execution_engine ("Failed to send request to egd socket"));
202 while (count != request [1]) {
204 received = read (file, buffer + offset, request [1] - count);
208 } else if (received < 0 && errno == EINTR) {
212 g_warning ("Receive egd request failed %d", errno);
213 mono_raise_exception (mono_get_exception_execution_engine ("Failed to get response from egd socket"));
217 buffer_size -= request [1];
224 mono_rand_open (void)
226 static gint32 status = 0;
227 if (status != 0 || InterlockedCompareExchange (&status, 1, 0) != 0) {
229 mono_thread_info_yield ();
233 #ifdef NAME_DEV_URANDOM
234 file = open (NAME_DEV_URANDOM, O_RDONLY);
236 #ifdef NAME_DEV_RANDOM
238 file = open (NAME_DEV_RANDOM, O_RDONLY);
241 use_egd = g_getenv("MONO_EGD_SOCKET") != NULL;
249 mono_rand_init (guchar *seed, gint seed_size)
251 // file < 0 is expected in the egd case
252 return (!use_egd && file < 0) ? NULL : GINT_TO_POINTER (file);
256 mono_rand_try_get_bytes (gpointer *handle, guchar *buffer, gint buffer_size)
261 const char *socket_path = g_getenv ("MONO_EGD_SOCKET");
262 /* exception will be thrown in managed code */
263 if (socket_path == NULL) {
267 get_entropy_from_egd (socket_path, buffer, buffer_size);
269 /* Read until the buffer is filled. This may block if using NAME_DEV_RANDOM. */
274 err = read (file, buffer + count, buffer_size - count);
278 g_warning("Entropy error! Error in read (%s).", strerror (errno));
279 /* exception will be thrown in managed code */
283 } while (count < buffer_size);
289 mono_rand_close (gpointer provider)
299 mono_rand_open (void)
301 static gint32 status = 0;
302 if (status != 0 || InterlockedCompareExchange (&status, 1, 0) != 0) {
304 mono_thread_info_yield ();
316 mono_rand_init (guchar *seed, gint seed_size)
318 return "srand"; // NULL will be interpreted as failure; return arbitrary nonzero pointer
322 mono_rand_try_get_bytes (gpointer *handle, guchar *buffer, gint buffer_size)
327 if (buffer_size - count >= sizeof (gint32) && RAND_MAX >= 0xFFFFFFFF) {
328 *(gint32*) buffer = rand();
329 count += sizeof (gint32);
330 buffer += sizeof (gint32) / sizeof (guchar);
331 } else if (buffer_size - count >= sizeof (gint16) && RAND_MAX >= 0xFFFF) {
332 *(gint16*) buffer = rand();
333 count += sizeof (gint16);
334 buffer += sizeof (gint16) / sizeof (guchar);
335 } else if (buffer_size - count >= sizeof (gint8) && RAND_MAX >= 0xFF) {
336 *(gint8*) buffer = rand();
337 count += sizeof (gint8);
338 buffer += sizeof (gint8) / sizeof (guchar);
340 } while (count < buffer_size);
346 mono_rand_close (gpointer provider)
353 * mono_rand_try_get_uint32:
354 * @handle: A pointer to an RNG handle. Handle is set to NULL on failure.
355 * @val: A pointer to a 32-bit unsigned int, to which the result will be written.
356 * @min: Result will be greater than or equal to this value.
357 * @max: Result will be less than or equal to this value.
359 * Returns: FALSE on failure, TRUE on success.
361 * Extracts one 32-bit unsigned int from an RNG handle.
364 mono_rand_try_get_uint32 (gpointer *handle, guint32 *val, guint32 min, guint32 max)
367 if (!mono_rand_try_get_bytes (handle, (guchar*) val, sizeof (guint32)))
370 double randomDouble = ((gdouble) *val) / ( ((double)G_MAXUINT32) + 1 ); // Range is [0,1)
371 *val = (guint32) (randomDouble * (max - min + 1) + min);
373 g_assert (*val >= min);
374 g_assert (*val <= max);