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