r288: combination of BUG 1081 and patch from J. Klinger -- added remove_duplicate_gid...
[tprouty/samba.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
25 static unsigned char hash[258];
26 static uint32 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 v1, v2; struct timeval tval; pid_t mypid;
138         struct passwd *pw;
139
140         if (use_fd) {
141                 if (fd != -1)
142                         return fd;
143
144                 fd = sys_open( "/dev/urandom", O_RDONLY,0);
145                 if(fd >= 0)
146                         return fd;
147         }
148
149         /* Add in some secret file contents */
150
151         do_filehash("/etc/shadow", &seed_inbuf[0]);
152         do_filehash(lp_smb_passwd_file(), &seed_inbuf[16]);
153
154         /*
155          * Add in the root encrypted password.
156          * On any system where security is taken
157          * seriously this will be secret.
158          */
159
160         pw = getpwnam_alloc("root");
161         if (pw && pw->pw_passwd) {
162                 size_t i;
163                 unsigned char md4_tmp[16];
164                 mdfour(md4_tmp, (unsigned char *)pw->pw_passwd, strlen(pw->pw_passwd));
165                 for (i=0;i<16;i++)
166                         seed_inbuf[8+i] ^= md4_tmp[i];
167                 passwd_free(&pw);
168         }
169
170         /*
171          * Add the counter, time of day, and pid.
172          */
173
174         GetTimeOfDay(&tval);
175         mypid = sys_getpid();
176         v1 = (counter++) + mypid + tval.tv_sec;
177         v2 = (counter++) * mypid + tval.tv_usec;
178
179         SIVAL(seed_inbuf, 32, v1 ^ IVAL(seed_inbuf, 32));
180         SIVAL(seed_inbuf, 36, v2 ^ IVAL(seed_inbuf, 36));
181
182         /*
183          * Add any user-given reseed data.
184          */
185
186         if (reseed_data) {
187                 size_t i;
188                 for (i = 0; i < sizeof(seed_inbuf); i++)
189                         seed_inbuf[i] ^= reseed_data[i % reseed_data_size];
190         }
191
192         seed_random_stream(seed_inbuf, sizeof(seed_inbuf));
193
194         return -1;
195 }
196
197 /*******************************************************************
198  Interface to the (hopefully) good crypto random number generator.
199 ********************************************************************/
200
201 void generate_random_buffer( unsigned char *out, int len, BOOL do_reseed_now)
202 {
203         static BOOL done_reseed = False;
204         static int urand_fd = -1;
205         unsigned char md4_buf[64];
206         unsigned char tmp_buf[16];
207         unsigned char *p;
208
209         if(!done_reseed || do_reseed_now) {
210                 urand_fd = do_reseed(True, urand_fd);
211                 done_reseed = True;
212         }
213
214         if (urand_fd != -1 && len > 0) {
215
216                 if (read(urand_fd, out, len) == len)
217                         return; /* len bytes of random data read from urandom. */
218
219                 /* Read of urand error, drop back to non urand method. */
220                 close(urand_fd);
221                 urand_fd = -1;
222                 do_reseed(False, -1);
223                 done_reseed = True;
224         }
225
226         /*
227          * Generate random numbers in chunks of 64 bytes,
228          * then md4 them & copy to the output buffer.
229          * This way the raw state of the stream is never externally
230          * seen.
231          */
232
233         p = out;
234         while(len > 0) {
235                 int copy_len = len > 16 ? 16 : len;
236
237                 get_random_stream(md4_buf, sizeof(md4_buf));
238                 mdfour(tmp_buf, md4_buf, sizeof(md4_buf));
239                 memcpy(p, tmp_buf, copy_len);
240                 p += copy_len;
241                 len -= copy_len;
242         }
243 }
244
245 /*******************************************************************
246  Use the random number generator to generate a random string.
247 ********************************************************************/
248
249 static char c_list[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_-#.,";
250
251 char *generate_random_str(size_t len)
252 {
253         static unsigned char retstr[256];
254         size_t i;
255
256         memset(retstr, '\0', sizeof(retstr));
257
258         if (len > sizeof(retstr)-1)
259                 len = sizeof(retstr) -1;
260         generate_random_buffer( retstr, len, False);
261         for (i = 0; i < len; i++)
262                 retstr[i] = c_list[ retstr[i] % (sizeof(c_list)-1) ];
263
264         retstr[i] = '\0';
265
266         return (char *)retstr;
267 }