r10421: following on discussions with simo, I have worked out a way of
[ira/wip.git] / source / lib / genrand.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Functions to create reasonable random numbers for crypto use.
5
6    Copyright (C) Jeremy Allison 2001
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24 #include "system/iconv.h"
25 #include "system/filesys.h"
26 #include "lib/crypto/crypto.h"
27
28 static unsigned char hash[258];
29 static uint32_t counter;
30
31 static BOOL done_reseed = False;
32 static void (*reseed_callback)(int *newseed);
33
34 /**************************************************************** 
35  Copy any user given reseed data.
36 *****************************************************************/
37
38 void set_rand_reseed_callback(void (*fn)(int *))
39 {
40         reseed_callback = fn;
41         set_need_random_reseed();
42 }
43
44 void set_need_random_reseed(void)
45 {
46         done_reseed = False;
47 }
48
49 static void get_rand_reseed_data(int *reseed_data)
50 {
51         if (reseed_callback) {
52                 reseed_callback(reseed_data);
53         } else {
54                 *reseed_data = 0;
55         }
56 }
57
58 /**************************************************************** 
59  Setup the seed.
60 *****************************************************************/
61
62 static void seed_random_stream(unsigned char *seedval, size_t seedlen)
63 {
64         unsigned char j = 0;
65         size_t ind;
66
67         for (ind = 0; ind < 256; ind++)
68                 hash[ind] = (unsigned char)ind;
69
70         for( ind = 0; ind < 256; ind++) {
71                 unsigned char tc;
72
73                 j += (hash[ind] + seedval[ind%seedlen]);
74
75                 tc = hash[ind];
76                 hash[ind] = hash[j];
77                 hash[j] = tc;
78         }
79
80         hash[256] = 0;
81         hash[257] = 0;
82 }
83
84 /**************************************************************** 
85  Get datasize bytes worth of random data.
86 *****************************************************************/
87
88 static void get_random_stream(unsigned char *data, size_t datasize)
89 {
90         unsigned char index_i = hash[256];
91         unsigned char index_j = hash[257];
92         size_t ind;
93
94         for( ind = 0; ind < datasize; ind++) {
95                 unsigned char tc;
96                 unsigned char t;
97
98                 index_i++;
99                 index_j += hash[index_i];
100
101                 tc = hash[index_i];
102                 hash[index_i] = hash[index_j];
103                 hash[index_j] = tc;
104
105                 t = hash[index_i] + hash[index_j];
106                 data[ind] = hash[t];
107         }
108
109         hash[256] = index_i;
110         hash[257] = index_j;
111 }
112
113 /****************************************************************
114  Get a 16 byte hash from the contents of a file.  
115
116  Note that the hash is initialised, because the extra entropy is not
117  worth the valgrind pain.
118 *****************************************************************/
119
120 static void do_filehash(const char *fname, unsigned char *the_hash)
121 {
122         unsigned char buf[1011]; /* deliberate weird size */
123         unsigned char tmp_md4[16];
124         int fd, n;
125
126         ZERO_STRUCT(tmp_md4);
127
128         fd = open(fname,O_RDONLY,0);
129         if (fd == -1)
130                 return;
131
132         while ((n = read(fd, (char *)buf, sizeof(buf))) > 0) {
133                 mdfour(tmp_md4, buf, n);
134                 for (n=0;n<16;n++)
135                         the_hash[n] ^= tmp_md4[n];
136         }
137         close(fd);
138 }
139
140 /**************************************************************
141  Try and get a good random number seed. Try a number of
142  different factors. Firstly, try /dev/urandom - use if exists.
143
144  We use /dev/urandom as a read of /dev/random can block if
145  the entropy pool dries up. This leads clients to timeout
146  or be very slow on connect.
147
148  If we can't use /dev/urandom then seed the stream random generator
149  above...
150 **************************************************************/
151
152 static int do_reseed(BOOL use_fd, int fd)
153 {
154         unsigned char seed_inbuf[40];
155         uint32_t v1, v2; struct timeval tval; pid_t mypid;
156         int reseed_data = 0;
157
158         if (use_fd) {
159                 if (fd != -1)
160                         return fd;
161
162                 fd = open( "/dev/urandom", O_RDONLY,0);
163                 if(fd >= 0)
164                         return fd;
165         }
166
167         /* Add in some secret file contents */
168
169         do_filehash("/etc/shadow", &seed_inbuf[0]);
170
171         /*
172          * Add the counter, time of day, and pid.
173          */
174
175         GetTimeOfDay(&tval);
176         mypid = getpid();
177         v1 = (counter++) + mypid + tval.tv_sec;
178         v2 = (counter++) * mypid + tval.tv_usec;
179
180         SIVAL(seed_inbuf, 32, v1 ^ IVAL(seed_inbuf, 32));
181         SIVAL(seed_inbuf, 36, v2 ^ IVAL(seed_inbuf, 36));
182
183         /*
184          * Add any user-given reseed data.
185          */
186
187         get_rand_reseed_data(&reseed_data);
188         if (reseed_data) {
189                 size_t i;
190                 for (i = 0; i < sizeof(seed_inbuf); i++)
191                         seed_inbuf[i] ^= ((char *)(&reseed_data))[i % sizeof(reseed_data)];
192         }
193
194         seed_random_stream(seed_inbuf, sizeof(seed_inbuf));
195
196         return -1;
197 }
198
199 /*
200  Interface to the (hopefully) good crypto random number generator.
201 */
202 void generate_random_buffer(uint8_t *out, int len)
203 {
204         static int urand_fd = -1;
205         unsigned char md4_buf[64];
206         unsigned char tmp_buf[16];
207         unsigned char *p;
208
209         if(!done_reseed) {
210                 urand_fd = do_reseed(True, urand_fd);
211                 done_reseed = True;
212         }
213
214         if (urand_fd != -1 && len > 0) {
215
216                 if (read(urand_fd, out, len) == len)
217                         return; /* len bytes of random data read from urandom. */
218
219                 /* Read of urand error, drop back to non urand method. */
220                 close(urand_fd);
221                 urand_fd = -1;
222                 do_reseed(False, -1);
223                 done_reseed = True;
224         }
225
226         /*
227          * Generate random numbers in chunks of 64 bytes,
228          * then md4 them & copy to the output buffer.
229          * This way the raw state of the stream is never externally
230          * seen.
231          */
232
233         p = out;
234         while(len > 0) {
235                 int copy_len = len > 16 ? 16 : len;
236
237                 get_random_stream(md4_buf, sizeof(md4_buf));
238                 mdfour(tmp_buf, md4_buf, sizeof(md4_buf));
239                 memcpy(p, tmp_buf, copy_len);
240                 p += copy_len;
241                 len -= copy_len;
242         }
243 }
244
245 /*
246   generate a single random uint32_t
247 */
248 uint32_t generate_random(void)
249 {
250         uint8_t v[4];
251         generate_random_buffer(v, 4);
252         return IVAL(v, 0);
253 }
254
255
256 /*
257   very basic password quality checker
258 */
259 BOOL check_password_quality(const char *s)
260 {
261         int has_digit=0, has_capital=0, has_lower=0;
262         while (*s) {
263                 if (isdigit((unsigned char)*s)) {
264                         has_digit++;
265                 } else if (isupper((unsigned char)*s)) {
266                         has_capital++;
267                 } else if (islower((unsigned char)*s)) {
268                         has_lower++;
269                 }
270                 s++;
271         }
272
273         return has_digit && has_lower && has_capital;
274 }
275
276 /*******************************************************************
277  Use the random number generator to generate a random string.
278 ********************************************************************/
279
280 char *generate_random_str_list(TALLOC_CTX *mem_ctx, size_t len, const char *list)
281 {
282         size_t i;
283         size_t list_len = strlen(list);
284
285         char *retstr = talloc_array(mem_ctx, char, len + 1);
286         if (!retstr) return NULL;
287
288         generate_random_buffer((uint8_t *)retstr, len);
289         for (i = 0; i < len; i++) {
290                 retstr[i] = list[retstr[i] % list_len];
291         }
292         retstr[i] = '\0';
293
294         return retstr;
295 }
296
297 char *generate_random_str(TALLOC_CTX *mem_ctx, size_t len)
298 {
299         char *retstr;
300         const char *c_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_-#.,";
301
302 again:
303         retstr = generate_random_str_list(mem_ctx, len, c_list);
304         if (!retstr) return NULL;
305
306         /* we need to make sure the random string passes basic quality tests
307            or it might be rejected by windows as a password */
308         if (len >= 7 && !check_password_quality(retstr)) {
309                 talloc_free(retstr);
310                 goto again;
311         }
312
313         return retstr;
314 }