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