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