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