This commit was manufactured by cvs2svn to create branch 'mono-1-0'.
[mono.git] / mono / metadata / rand.c
1 /*
2  * rand.c: System.Security.Cryptography.RNGCryptoServiceProvider support
3  *
4  * Authors:
5  *      Mark Crichton (crichton@gimp.org)
6  *      Patrik Torstensson (p@rxc.se)
7  *      Sebastien Pouliot (sebastien@ximian.com)
8  *
9  * (C) 2001 Ximian, Inc.
10  * (C) 2004 Novell (http://www.novell.com)
11  */
12
13 #include <config.h>
14 #include <glib.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <fcntl.h>
18 #include <unistd.h>
19
20 #include <mono/metadata/object.h>
21 #include <mono/metadata/rand.h>
22 #include <mono/metadata/exception.h>
23
24 #if !defined(PLATFORM_WIN32)
25 #include <sys/socket.h>
26 #include <sys/un.h>
27 #include <errno.h>
28
29 static void
30 get_entropy_from_server (const char *path, guchar *buf, int len)
31 {
32     int file;
33     gint ret;
34     guint offset = 0;
35     struct sockaddr_un egd_addr;
36
37     file = socket (PF_UNIX, SOCK_STREAM, 0);
38     if (file < 0)
39         ret = -1;
40     else {
41         egd_addr.sun_family = AF_UNIX;
42         strncpy (egd_addr.sun_path, path, MONO_SIZEOF_SUNPATH - 1);
43         egd_addr.sun_path [MONO_SIZEOF_SUNPATH-1] = '\0';
44         ret = connect (file, (struct sockaddr *)&egd_addr, sizeof(egd_addr));
45     }
46     if (ret == -1) {
47         if (file >= 0)
48             close (file);
49         g_warning ("Entropy problem! Can't create or connect to egd socket %s", path);
50         mono_raise_exception (mono_get_exception_execution_engine ("Failed to open egd socket"));
51     }
52
53     while (len > 0) {
54         guchar request[2];
55         gint count = 0;
56
57         request [0] = 2; /* block until daemon can return enough entropy */
58         request [1] = len < 255 ? len : 255;
59         while (count < 2) {
60             int sent = write (file, request + count, 2 - count);
61             if (sent >= 0)
62                 count += sent;
63             else if (errno == EINTR)
64                 continue;
65             else {
66                 close (file);
67                 g_warning ("Send egd request failed %d", errno);
68                 mono_raise_exception (mono_get_exception_execution_engine ("Failed to send request to egd socket"));
69             }
70         }
71
72         count = 0;
73         while (count != request [1]) {
74             int received;
75             received = read(file, buf + offset, request [1] - count);
76             if (received > 0) {
77                 count += received;
78                 offset += received;
79             } else if (received < 0 && errno == EINTR) {
80                 continue;
81             } else {
82                 close (file);
83                 g_warning ("Receive egd request failed %d", errno);
84                 mono_raise_exception (mono_get_exception_execution_engine ("Failed to get response from egd socket"));
85             }
86         }
87
88         len -= request [1];
89     }
90
91     close (file);
92 }
93 #endif
94
95 #if defined (PLATFORM_WIN32)
96
97 #include <WinCrypt.h>
98
99 #ifndef PROV_INTEL_SEC
100 #define PROV_INTEL_SEC          22
101 #endif
102 #ifndef CRYPT_VERIFY_CONTEXT
103 #define CRYPT_VERIFY_CONTEXT    0xF0000000
104 #endif
105
106 gpointer
107 ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_RngInitialize (MonoArray *seed)
108 {
109         HCRYPTPROV provider = 0;
110
111         /* There is no need to create a container for just random data,
112            so we can use CRYPT_VERIFY_CONTEXT (one call) see: 
113            http://blogs.msdn.com/dangriff/archive/2003/11/19/51709.aspx */
114
115         /* We first try to use the Intel PIII RNG if drivers are present */
116         if (!CryptAcquireContext (&provider, NULL, NULL, PROV_INTEL_SEC, CRYPT_VERIFY_CONTEXT)) {
117                 /* not a PIII or no drivers available, use default RSA CSP */
118                 if (!CryptAcquireContext (&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFY_CONTEXT)) {
119                         provider = 0;
120                         /* exception will be thrown in managed code */
121                 }
122         }
123
124         /* seed the CSP with the supplied buffer (if present) */
125         if ((provider != 0) && (seed)) {
126                 guint32 len = mono_array_length (seed);
127                 guchar *buf = mono_array_addr (seed, guchar, 0);
128                 /* the call we replace the seed with random - this isn't what is
129                    expected from the class library user */
130                 guchar *data = g_malloc (len);
131                 if (data) {
132                         memcpy (data, buf, len);
133                         /* add seeding material to the RNG */
134                         CryptGenRandom (provider, len, data);
135                         /* zeroize and free */
136                         memset (data, 0, len);
137                         g_free (data);
138                 }
139         }
140
141         return (gpointer) provider;     
142 }
143
144 gpointer
145 ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_RngGetBytes (gpointer handle, MonoArray *arry)
146 {
147         HCRYPTPROV provider = (HCRYPTPROV) handle;
148         guint32 len = mono_array_length (arry);
149         guchar *buf = mono_array_addr (arry, guchar, 0);
150
151         if (!CryptGenRandom (provider, len, buf)) {
152                 CryptReleaseContext (provider, 0);
153                 /* we may have lost our context with CryptoAPI, but all hope isn't lost yet! */
154                 provider = ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_RngInitialize (NULL);
155                 if (!CryptGenRandom (provider, len, buf)) {
156                         CryptReleaseContext (provider, 0);
157                         provider = 0;
158                         /* exception will be thrown in managed code */
159                 }
160         } 
161 }
162
163 void
164 ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_RngClose (gpointer handle) 
165 {
166         CryptReleaseContext ((HCRYPTPROV) handle, 0);
167 }
168
169 #else
170
171 #ifndef NAME_DEV_URANDOM
172 #define NAME_DEV_URANDOM "/dev/urandom"
173 #endif
174
175 static gboolean egd = FALSE;
176
177 gpointer
178 ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_RngInitialize (MonoArray *seed)
179 {
180         gint file = -1;
181
182         if (egd)
183                 return -1;
184
185 #if defined (NAME_DEV_URANDOM)
186         file = open (NAME_DEV_URANDOM, O_RDONLY);
187 #endif
188
189 #if defined (NAME_DEV_RANDOM)
190         if (file < 0)
191                 file = open (NAME_DEV_RANDOM, O_RDONLY);
192 #endif
193
194         if (file < 0) {
195                 const char *socket_path = g_getenv("MONO_EGD_SOCKET");
196                 egd = (socket_path != NULL);
197                 return -1;
198         }
199
200         /* if required exception will be thrown in managed code */
201         return ((file < 0) ? NULL : (gpointer) file);
202 }
203
204 gpointer 
205 ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_RngGetBytes (gpointer handle, MonoArray *arry)
206 {
207         gint file = (gint) handle;
208         guint32 len = mono_array_length (arry);
209         guchar *buf = mono_array_addr (arry, guchar, 0);
210
211         if (egd) {
212                 const char *socket_path = getenv ("MONO_EGD_SOCKET");
213                 /* exception will be thrown in managed code */
214                 if (socket_path == NULL)
215                         return NULL; 
216                 get_entropy_from_server (socket_path, mono_array_addr (arry, guchar, 0), mono_array_length (arry));
217                 return -1;
218         }
219         else {
220                 /* Read until the buffer is filled. This may block if using NAME_DEV_RANDOM. */
221                 gint count = 0;
222                 gint err;
223
224                 do {
225                         err = read (file, buf + count, len - count);
226                         count += err;
227                 } while (err >= 0 && count < len);
228
229                 if (err < 0) {
230                         g_warning("Entropy error! Error in read (%s).", strerror (errno));
231                         /* exception will be thrown in managed code */
232                         return NULL;
233                 }
234         }
235
236         /* We do not support PRNG seeding right now but the class library is this */
237
238         return handle;  
239 }
240
241 void
242 ves_icall_System_Security_Cryptography_RNGCryptoServiceProvider_RngClose (gpointer handle) 
243 {
244         if (!egd)
245                 close ((gint) handle);
246 }
247
248 #endif /* OS definition */