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