first pass at updating head branch to be to be the same as the SAMBA_2_0 branch
[kai/samba.git] / source / lib / genrand.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4
5    Functions to create reasonable random numbers for crypto use.
6
7    Copyright (C) Jeremy Allison 1998
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25
26 extern int DEBUGLEVEL;
27 static uint32 counter = 0;
28
29 /****************************************************************
30 get a 16 byte hash from the contents of a file
31 Note that the hash is not initialised.
32 *****************************************************************/
33 static void do_filehash(char *fname, unsigned char *hash)
34 {
35         unsigned char buf[1011]; /* deliberate weird size */
36         unsigned char tmp_md4[16];
37         int fd, n;
38
39         fd = sys_open(fname,O_RDONLY,0);
40         if (fd == -1) return;
41
42         while ((n = read(fd, (char *)buf, sizeof(buf))) > 0) {
43                 mdfour(tmp_md4, buf, n);
44                 for (n=0;n<16;n++)
45                         hash[n] ^= tmp_md4[n];
46         }
47         close(fd);
48 }
49
50
51
52 /****************************************************************
53  Try and get a seed by looking at the atimes of files in a given
54  directory. XOR them into the buf array.
55 *****************************************************************/
56
57 static void do_dirrand(char *name, unsigned char *buf, int buf_len)
58 {
59   DIR *dp = opendir(name);
60   pstring fullname;
61   int len_left;
62   int fullname_len;
63   char *pos;
64
65   pstrcpy(fullname, name);
66   fullname_len = strlen(fullname);
67
68   if(fullname_len + 2 > sizeof(pstring))
69     return;
70
71   if(fullname[fullname_len] != '/') {
72     fullname[fullname_len] = '/';
73     fullname[fullname_len+1] = '\0';
74     fullname_len = strlen(fullname);
75   }
76
77   len_left = sizeof(pstring) - fullname_len - 1;
78   pos = &fullname[fullname_len];
79
80   if(dp != NULL) {
81     char *p;
82
83     while ((p = readdirname(dp))) {           
84       SMB_STRUCT_STAT st;
85
86       if(strlen(p) <= len_left)
87         pstrcpy(pos, p);
88
89       if(sys_stat(fullname,&st) == 0) {
90         SIVAL(buf, ((counter * 4)%(buf_len-4)), 
91               IVAL(buf,((counter * 4)%(buf_len-4))) ^ st.st_atime);
92         counter++;
93         DEBUG(10,("do_dirrand: value from file %s.\n", fullname));
94       }
95     }
96     closedir(dp); 
97   }
98 }
99
100 /**************************************************************
101  Try and get a good random number seed. Try a number of
102  different factors. Firstly, try /dev/urandom and try and
103  read from this. If this fails iterate through /tmp and
104  /dev and XOR all the file timestamps. Next add in
105  a hash of the contents of /etc/shadow and the smb passwd
106  file and a combination of pid and time of day (yes I know this
107  sucks :-). Finally md4 the result.
108
109  We use /dev/urandom as a read of /dev/random can block if
110  the entropy pool dries up. This leads clients to timeout
111  or be very slow on connect.
112
113  The result goes in a 16 byte buffer passed from the caller
114 **************************************************************/
115
116 static uint32 do_reseed(unsigned char *md4_outbuf)
117 {
118   unsigned char md4_inbuf[40];
119   BOOL got_random = False;
120   uint32 v1, v2, ret;
121   int fd;
122   struct timeval tval;
123   pid_t mypid;
124   struct passwd *pw;
125
126   memset(md4_inbuf, '\0', sizeof(md4_inbuf));
127
128   fd = sys_open( "/dev/urandom", O_RDONLY,0);
129   if(fd >= 0) {
130     /* 
131      * We can use /dev/urandom !
132      */
133     if(read(fd, md4_inbuf, 40) == 40) {
134       got_random = True;
135       DEBUG(10,("do_reseed: got 40 bytes from /dev/urandom.\n"));
136     }
137     close(fd);
138   }
139
140   if(!got_random) {
141     /*
142      * /dev/urandom failed - try /dev for timestamps.
143      */
144     do_dirrand("/dev", md4_inbuf, sizeof(md4_inbuf));
145   }
146
147   /* possibly add in some secret file contents */
148   do_filehash("/etc/shadow", &md4_inbuf[0]);
149   do_filehash(lp_smb_passwd_file(), &md4_inbuf[16]);
150
151   /* add in the root encrypted password. On any system where security is taken
152      seriously this will be secret */
153   pw = sys_getpwnam("root");
154   if (pw && pw->pw_passwd) {
155           int i;
156           unsigned char md4_tmp[16];
157           mdfour(md4_tmp, (unsigned char *)pw->pw_passwd, strlen(pw->pw_passwd));
158           for (i=0;i<16;i++)
159                   md4_inbuf[8+i] ^= md4_tmp[i];
160   }
161
162   /*
163    * Finally add the counter, time of day, and pid.
164    */
165   GetTimeOfDay(&tval);
166   mypid = getpid();
167   v1 = (counter++) + mypid + tval.tv_sec;
168   v2 = (counter++) * mypid + tval.tv_usec;
169
170   SIVAL(md4_inbuf, 32, v1 ^ IVAL(md4_inbuf, 32));
171   SIVAL(md4_inbuf, 36, v2 ^ IVAL(md4_inbuf, 36));
172
173   mdfour(md4_outbuf, md4_inbuf, sizeof(md4_inbuf));
174
175   /*
176    * Return a 32 bit int created from XORing the
177    * 16 bit return buffer.
178    */
179
180   ret = IVAL(md4_outbuf, 0);
181   ret ^= IVAL(md4_outbuf, 4);
182   ret ^= IVAL(md4_outbuf, 8);
183   return (ret ^ IVAL(md4_outbuf, 12));
184 }
185
186 /*******************************************************************
187  Interface to the (hopefully) good crypto random number generator.
188 ********************************************************************/
189
190 void generate_random_buffer( unsigned char *out, int len, BOOL re_seed)
191 {
192   static BOOL done_reseed = False;
193   static unsigned char md4_buf[16];
194   unsigned char tmp_buf[16];
195   unsigned char *p;
196
197   if(!done_reseed || re_seed) {
198           sys_srandom(do_reseed(md4_buf));
199           done_reseed = True;
200   }
201
202   /*
203    * Generate random numbers in chunks of 64 bytes,
204    * then md4 them & copy to the output buffer.
205    * Added XOR with output from random, seeded
206    * by the original md4_buf. This is to stop the
207    * output from this function being the previous
208    * md4_buf md4'ed. The output from this function
209    * is often output onto the wire, and so it should
210    * not be possible to guess the next output from
211    * this function based on the previous output.
212    * XORing in the output from random(), seeded by
213    * the original md4 hash should stop this. JRA.
214    */
215
216   p = out;
217   while(len > 0) {
218     int i;
219     int copy_len = len > 16 ? 16 : len;
220     mdfour(tmp_buf, md4_buf, sizeof(md4_buf));
221     memcpy(md4_buf, tmp_buf, sizeof(md4_buf));
222     /* XOR in output from random(). */
223     for(i = 0; i < 4; i++)
224       SIVAL(tmp_buf, i*4, (IVAL(tmp_buf, i*4) ^ (uint32)sys_random()));
225     memcpy(p, tmp_buf, copy_len);
226     p += copy_len;
227     len -= copy_len;
228   }
229 }