Prefer /dev/random on MacOS since it's always there and have good performance.
[metze/heimdal/wip.git] / lib / hcrypto / rand.c
1 /*
2  * Copyright (c) 2006 - 2007 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden).
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * 3. Neither the name of the Institute nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #include <config.h>
36 #endif
37
38 RCSID("$Id$");
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <rand.h>
43 #include <randi.h>
44
45 #include <roken.h>
46
47 #ifndef O_BINARY
48 #define O_BINARY 0
49 #endif
50
51 /**
52  * @page page_rand RAND - random number
53  *
54  * See the library functions here: @ref hcrypto_rand
55  */
56
57 const static RAND_METHOD *selected_meth = NULL;
58 static ENGINE *selected_engine = NULL;
59
60 static void
61 init_method(void)
62 {
63     if (selected_meth != NULL)
64         return;
65 #ifdef __APPLE__
66     selected_meth = &hc_rand_unix_method;
67 #else
68     selected_meth = &hc_rand_fortuna_method;
69 #endif
70 }
71
72 /**
73  * Seed that random number generator. Secret material can securely be
74  * feed into the function, they will never be returned.
75  *
76  * @param indata seed data
77  * @param size length seed data
78  *
79  * @ingroup hcrypto_rand
80  */
81
82 void
83 RAND_seed(const void *indata, size_t size)
84 {
85     init_method();
86     (*selected_meth->seed)(indata, size);
87 }
88
89 /**
90  * Get a random block from the random generator, can be used for key material.
91  *
92  * @param outdata random data
93  * @param size length random data
94  *
95  * @return 1 on success, 0 on failure.
96  *
97  * @ingroup hcrypto_rand
98  */
99 int
100 RAND_bytes(void *outdata, size_t size)
101 {
102     init_method();
103     return (*selected_meth->bytes)(outdata, size);
104 }
105
106 /**
107  * Reset and free memory used by the random generator.
108  *
109  * @ingroup hcrypto_rand
110  */
111
112 void
113 RAND_cleanup(void)
114 {
115     const RAND_METHOD *meth = selected_meth;
116     ENGINE *engine = selected_engine;
117
118     selected_meth = NULL;
119     selected_engine = NULL;
120
121     if (meth)
122         (*meth->cleanup)();
123     if (engine)
124         ENGINE_finish(engine);
125 }
126
127 /**
128  * Seed that random number generator. Secret material can securely be
129  * feed into the function, they will never be returned.
130  *
131  * @param indata the input data.
132  * @param size size of in data.
133  * @param entropi entropi in data.
134  *
135  *
136  * @ingroup hcrypto_rand
137  */
138
139 void
140 RAND_add(const void *indata, size_t size, double entropi)
141 {
142     init_method();
143     (*selected_meth->add)(indata, size, entropi);
144 }
145
146 /**
147  * Get a random block from the random generator, should NOT be used for key material.
148  *
149  * @param outdata random data
150  * @param size length random data
151  *
152  * @return 1 on success, 0 on failure.
153  *
154  * @ingroup hcrypto_rand
155  */
156
157 int
158 RAND_pseudo_bytes(void *outdata, size_t size)
159 {
160     init_method();
161     return (*selected_meth->pseudorand)(outdata, size);
162 }
163
164 /**
165  * Return status of the random generator
166  *
167  * @return 1 if the random generator can deliver random data.
168  *
169  * @ingroup hcrypto_rand
170  */
171
172 int
173 RAND_status(void)
174 {
175     init_method();
176     return (*selected_meth->status)();
177 }
178
179 /**
180  * Set the default random method.
181  *
182  * @param meth set the new default method.
183  *
184  * @return 1 on success.
185  *
186  * @ingroup hcrypto_rand
187  */
188
189 int
190 RAND_set_rand_method(const RAND_METHOD *meth)
191 {
192     const RAND_METHOD *old = selected_meth;
193     selected_meth = meth;
194     if (old)
195         (*old->cleanup)();
196     if (selected_engine) {
197         ENGINE_finish(selected_engine);
198         selected_engine = NULL;
199     }
200     return 1;
201 }
202
203 /**
204  * Get the default random method.
205  *
206  * @ingroup hcrypto_rand
207  */
208
209 const RAND_METHOD *
210 RAND_get_rand_method(void)
211 {
212     init_method();
213     return selected_meth;
214 }
215
216 /**
217  * Set the default random method from engine.
218  *
219  * @param engine use engine, if NULL is passed it, old method and engine is cleared.
220  *
221  * @return 1 on success, 0 on failure.
222  *
223  * @ingroup hcrypto_rand
224  */
225
226 int
227 RAND_set_rand_engine(ENGINE *engine)
228 {
229     const RAND_METHOD *meth, *old = selected_meth;
230
231     if (engine) {
232         ENGINE_up_ref(engine);
233         meth = ENGINE_get_RAND(engine);
234         if (meth == NULL) {
235             ENGINE_finish(engine);
236             return 0;
237         }
238     } else {
239         meth = NULL;
240     }
241
242     if (old)
243         (*old->cleanup)();
244
245     if (selected_engine)
246         ENGINE_finish(selected_engine);
247
248     selected_engine = engine;
249     selected_meth = meth;
250
251     return 1;
252 }
253
254 #define RAND_FILE_SIZE 1024
255
256 /**
257  * Load a a file and feed it into RAND_seed().
258  *
259  * @param filename name of file to read.
260  * @param size minimum size to read.
261  *
262  * @ingroup hcrypto_rand
263  */
264
265 int
266 RAND_load_file(const char *filename, size_t size)
267 {
268     unsigned char buf[128];
269     size_t len;
270     ssize_t slen;
271     int fd;
272
273     fd = open(filename, O_RDONLY | O_BINARY, 0600);
274     if (fd < 0)
275         return 0;
276     rk_cloexec(fd);
277     len = 0;
278     while(len < size) {
279         slen = read(fd, buf, sizeof(buf));
280         if (slen <= 0)
281             break;
282         RAND_seed(buf, slen);
283         len += slen;
284     }
285     close(fd);
286
287     return len ? 1 : 0;
288 }
289
290 /**
291  * Write of random numbers to a file to store for later initiation with RAND_load_file().
292  *
293  * @param filename name of file to write.
294  *
295  * @return 1 on success and non-one on failure.
296  * @ingroup hcrypto_rand
297  */
298
299 int
300 RAND_write_file(const char *filename)
301 {
302     unsigned char buf[128];
303     size_t len;
304     int res = 0, fd;
305
306     fd = open(filename, O_WRONLY | O_CREAT | O_BINARY, 0600);
307     if (fd < 0)
308         return 0;
309     rk_cloexec(fd);
310
311     len = 0;
312     while(len < RAND_FILE_SIZE) {
313         res = RAND_bytes(buf, sizeof(buf));
314         if (res != 1)
315             break;
316         if (write(fd, buf, sizeof(buf)) != sizeof(buf)) {
317             res = 0;
318             break;
319         }
320         len += sizeof(buf);
321     }
322
323     close(fd);
324
325     return res;
326 }
327
328 /**
329  * Return the default random state filename for a user to use for
330  * RAND_load_file(), and RAND_write_file().
331  *
332  * @param filename buffer to hold file name.
333  * @param size size of buffer filename.
334  *
335  * @return the buffer filename or NULL on failure.
336  *
337  * @ingroup hcrypto_rand
338  */
339
340 const char *
341 RAND_file_name(char *filename, size_t size)
342 {
343     const char *e = NULL;
344     int pathp = 0, ret;
345
346     if (!issuid()) {
347         e = getenv("RANDFILE");
348         if (e == NULL) {
349             e = getenv("HOME");
350             if (e)
351                 pathp = 1;
352         }
353     }
354     /*
355      * Here we really want to call getpwuid(getuid()) but this will
356      * cause recursive lookups if the nss library uses
357      * gssapi/krb5/hcrypto to authenticate to the ldap servers.
358      */
359
360     if (e == NULL)
361         return NULL;
362
363     if (pathp)
364         ret = snprintf(filename, size, "%s/.rnd", e);
365     else
366         ret = snprintf(filename, size, "%s", e);
367
368     if (ret <= 0 || ret >= size)
369         return NULL;
370
371     return filename;
372 }