Import of old SSLeay release: SSLeay 0.8.1b
[openssl.git] / crypto / rand / md_rand.c
1 /* crypto/rand/md_rand.c */
2 /* Copyright (C) 1995-1997 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58
59 #include <stdio.h>
60 #include "cryptlib.h"
61 #include <sys/types.h>
62 #include <time.h>
63
64
65 #if !defined(USE_MD5_RAND) && !defined(USE_SHA1_RAND) && !defined(USE_MDC2_RAND) && !defined(USE_MD2_RAND)
66 #ifndef NO_MD5
67 #define USE_MD5_RAND
68 #elif !defined(NO_SHA1)
69 #define USE_SHA1_RAND
70 #elif !defined(NO_MDC2)
71 #define USE_MDC2_RAND
72 #elif !defined(NO_MD2)
73 #define USE_MD2_RAND
74 #else
75 We need a message digest of some type 
76 #endif
77 #endif
78
79 /* Changed how the state buffer used.  I now attempt to 'wrap' such
80  * that I don't run over the same locations the next time  go through
81  * the 1023 bytes - many thanks to
82  * Robert J. LeBlanc <rjl@renaissoft.com> for his comments
83  */
84
85 #if defined(USE_MD5_RAND)
86 #include "md5.h"
87 #define MD_DIGEST_LENGTH        MD5_DIGEST_LENGTH
88 #define MD_CTX                  MD5_CTX
89 #define MD_Init(a)              MD5_Init(a)
90 #define MD_Update(a,b,c)        MD5_Update(a,b,c)
91 #define MD_Final(a,b)           MD5_Final(a,b)
92 #elif defined(USE_SHA1_RAND)
93 #include "sha.h"
94 #define MD_DIGEST_LENGTH        SHA_DIGEST_LENGTH
95 #define MD_CTX                  SHA_CTX
96 #define MD_Init(a)              SHA1_Init(a)
97 #define MD_Update(a,b,c)        SHA1_Update(a,b,c)
98 #define MD_Final(a,b)           SHA1_Final(a,b)
99 #elif defined(USE_MDC2_RAND)
100 #include "mdc2.h"
101 #define MD_DIGEST_LENGTH        MDC2_DIGEST_LENGTH
102 #define MD_CTX                  MDC2_CTX
103 #define MD_Init(a)              MDC2_Init(a)
104 #define MD_Update(a,b,c)        MDC2_Update(a,b,c)
105 #define MD_Final(a,b)           MDC2_Final(a,b)
106 #elif defined(USE_MD2_RAND)
107 #include "md2.h"
108 #define MD_DIGEST_LENGTH        MD2_DIGEST_LENGTH
109 #define MD_CTX                  MD2_CTX
110 #define MD_Init(a)              MD2_Init(a)
111 #define MD_Update(a,b,c)        MD2_Update(a,b,c)
112 #define MD_Final(a,b)           MD2_Final(a,b)
113 #endif
114
115 #include "rand.h"
116
117 /*#define NORAND        1 */
118 /*#define PREDICT       1 */
119
120 #define STATE_SIZE      1023
121 static int state_num=0,state_index=0;
122 static unsigned char state[STATE_SIZE];
123 static unsigned char md[MD_DIGEST_LENGTH];
124 static int count=0;
125
126 char *RAND_version="RAND part of SSLeay 0.8.1b 29-Jun-1998";
127
128 void RAND_cleanup()
129         {
130         memset(state,0,STATE_SIZE);
131         state_num=0;
132         state_index=0;
133         memset(md,0,MD_DIGEST_LENGTH);
134         count=0;
135         }
136
137 void RAND_seed(buf,num)
138 unsigned char *buf;
139 int num;
140         {
141         int i,j,k,st_idx,st_num;
142         MD_CTX m;
143
144 #ifdef NORAND
145         return;
146 #endif
147
148         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
149         st_idx=state_index;
150         st_num=state_num;
151
152         state_index=(state_index+num);
153         if (state_index > STATE_SIZE)
154                 {
155                 state_index%=STATE_SIZE;
156                 state_num=STATE_SIZE;
157                 }
158         else if (state_num < STATE_SIZE)        
159                 {
160                 if (state_index > state_num)
161                         state_num=state_index;
162                 }
163         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
164
165         for (i=0; i<num; i+=MD_DIGEST_LENGTH)
166                 {
167                 j=(num-i);
168                 j=(j > MD_DIGEST_LENGTH)?MD_DIGEST_LENGTH:j;
169
170                 MD_Init(&m);
171                 MD_Update(&m,md,MD_DIGEST_LENGTH);
172                 k=(st_idx+j)-STATE_SIZE;
173                 if (k > 0)
174                         {
175                         MD_Update(&m,&(state[st_idx]),j-k);
176                         MD_Update(&m,&(state[0]),k);
177                         }
178                 else
179                         MD_Update(&m,&(state[st_idx]),j);
180                         
181                 MD_Update(&m,buf,j);
182                 MD_Final(md,&m);
183
184                 buf+=j;
185
186                 for (k=0; k<j; k++)
187                         {
188                         state[st_idx++]^=md[k];
189                         if (st_idx >= STATE_SIZE)
190                                 {
191                                 st_idx=0;
192                                 st_num=STATE_SIZE;
193                                 }
194                         }
195                 }
196         memset((char *)&m,0,sizeof(m));
197         }
198
199 void RAND_bytes(buf,num)
200 unsigned char *buf;
201 int num;
202         {
203         int i,j,k,st_num,st_idx;
204         MD_CTX m;
205         static int init=1;
206         unsigned long l;
207 #ifdef DEVRANDOM
208         FILE *fh;
209 #endif
210
211 #ifdef PREDICT
212         {
213         static unsigned char val=0;
214
215         for (i=0; i<num; i++)
216                 buf[i]=val++;
217         return;
218         }
219 #endif
220
221         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
222
223         if (init)
224                 {
225                 init=0;
226                 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
227                 /* put in some default random data, we need more than
228                  * just this */
229                 RAND_seed((unsigned char *)&m,sizeof(m));
230 #ifndef MSDOS
231                 l=getpid();
232                 RAND_seed((unsigned char *)&l,sizeof(l));
233                 l=getuid();
234                 RAND_seed((unsigned char *)&l,sizeof(l));
235 #endif
236                 l=time(NULL);
237                 RAND_seed((unsigned char *)&l,sizeof(l));
238
239 #ifdef DEVRANDOM
240                 /* 
241                  * Use a random entropy pool device.
242                  * Linux 1.3.x and FreeBSD-Current has 
243                  * this. Use /dev/urandom if you can
244                  * as /dev/random will block if it runs out
245                  * of random entries.
246                  */
247                 if ((fh = fopen(DEVRANDOM, "r")) != NULL)
248                         {
249                         unsigned char buf[32];
250
251                         fread((unsigned char *)buf,1,32,fh);
252                         /* we don't care how many bytes we read,
253                          * we will just copy the 'stack' if there is
254                          * nothing else :-) */
255                         fclose(fh);
256                         RAND_seed(buf,32);
257                         memset(buf,0,32);
258                         }
259 #endif
260 #ifdef PURIFY
261                 memset(state,0,STATE_SIZE);
262                 memset(md,0,MD_DIGEST_LENGTH);
263 #endif
264                 CRYPTO_w_lock(CRYPTO_LOCK_RAND);
265                 }
266
267         st_idx=state_index;
268         st_num=state_num;
269         state_index+=num;
270         if (state_index > state_num)
271                 state_index=(state_index%state_num);
272
273         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
274
275         while (num > 0)
276                 {
277                 j=(num >= MD_DIGEST_LENGTH/2)?MD_DIGEST_LENGTH/2:num;
278                 num-=j;
279                 MD_Init(&m);
280                 MD_Update(&m,&(md[MD_DIGEST_LENGTH/2]),MD_DIGEST_LENGTH/2);
281 #ifndef PURIFY
282                 MD_Update(&m,buf,j); /* purify complains */
283 #endif
284                 k=(st_idx+j)-st_num;
285                 if (k > 0)
286                         {
287                         MD_Update(&m,&(state[st_idx]),j-k);
288                         MD_Update(&m,&(state[0]),k);
289                         }
290                 else
291                         MD_Update(&m,&(state[st_idx]),j);
292                 MD_Final(md,&m);
293
294                 for (i=0; i<j; i++)
295                         {
296                         if (st_idx >= st_num)
297                                 st_idx=0;
298                         state[st_idx++]^=md[i];
299                         *(buf++)=md[i+MD_DIGEST_LENGTH/2];
300                         }
301                 }
302
303         MD_Init(&m);
304         MD_Update(&m,(unsigned char *)&count,sizeof(count)); count++;
305         MD_Update(&m,md,MD_DIGEST_LENGTH);
306         MD_Final(md,&m);
307         memset(&m,0,sizeof(m));
308         }
309
310 #ifdef WINDOWS
311 #include <windows.h>
312 #include <rand.h>
313
314 /*****************************************************************************
315  * Initialisation function for the SSL random generator.  Takes the contents
316  * of the screen as random seed.
317  *
318  * Created 960901 by Gertjan van Oosten, gertjan@West.NL, West Consulting B.V.
319  *
320  * Code adapted from
321  * <URL:http://www.microsoft.com/kb/developr/win_dk/q97193.htm>;
322  * the original copyright message is:
323  *
324 //   (C) Copyright Microsoft Corp. 1993.  All rights reserved.
325 //
326 //   You have a royalty-free right to use, modify, reproduce and
327 //   distribute the Sample Files (and/or any modified version) in
328 //   any way you find useful, provided that you agree that
329 //   Microsoft has no warranty obligations or liability for any
330 //   Sample Application Files which are modified.
331  */
332 /*
333  * I have modified the loading of bytes via RAND_seed() mechanism since
334  * the origional would have been very very CPU intensive since RAND_seed()
335  * does an MD5 per 16 bytes of input.  The cost to digest 16 bytes is the same
336  * as that to digest 56 bytes.  So under the old system, a screen of
337  * 1024*768*256 would have been CPU cost of approximatly 49,000 56 byte MD5
338  * digests or digesting 2.7 mbytes.  What I have put in place would
339  * be 48 16k MD5 digests, or efectivly 48*16+48 MD5 bytes or 816 kbytes
340  * or about 3.5 times as much.
341  * - eric 
342  */
343 void RAND_screen(void)
344 {
345   HDC           hScrDC;         /* screen DC */
346   HDC           hMemDC;         /* memory DC */
347   HBITMAP       hBitmap;        /* handle for our bitmap */
348   HBITMAP       hOldBitmap;     /* handle for previous bitmap */
349   BITMAP        bm;             /* bitmap properties */
350   unsigned int  size;           /* size of bitmap */
351   char          *bmbits;        /* contents of bitmap */
352   int           w;              /* screen width */
353   int           h;              /* screen height */
354   int           y;              /* y-coordinate of screen lines to grab */
355   int           n = 16;         /* number of screen lines to grab at a time */
356
357   /* Create a screen DC and a memory DC compatible to screen DC */
358   hScrDC = CreateDC("DISPLAY", NULL, NULL, NULL);
359   hMemDC = CreateCompatibleDC(hScrDC);
360
361   /* Get screen resolution */
362   w = GetDeviceCaps(hScrDC, HORZRES);
363   h = GetDeviceCaps(hScrDC, VERTRES);
364
365   /* Create a bitmap compatible with the screen DC */
366   hBitmap = CreateCompatibleBitmap(hScrDC, w, n);
367
368   /* Select new bitmap into memory DC */
369   hOldBitmap = SelectObject(hMemDC, hBitmap);
370
371   /* Get bitmap properties */
372   GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&bm);
373   size = (unsigned int)bm.bmWidthBytes * bm.bmHeight * bm.bmPlanes;
374
375   bmbits = Malloc(size);
376   if (bmbits) {
377     /* Now go through the whole screen, repeatedly grabbing n lines */
378     for (y = 0; y < h-n; y += n)
379         {
380         unsigned char md[MD_DIGEST_LENGTH];
381
382         /* Bitblt screen DC to memory DC */
383         BitBlt(hMemDC, 0, 0, w, n, hScrDC, 0, y, SRCCOPY);
384
385         /* Copy bitmap bits from memory DC to bmbits */
386         GetBitmapBits(hBitmap, size, bmbits);
387
388         /* Get the MD5 of the bitmap */
389         MD5(bmbits,size,md);
390
391         /* Seed the random generator with the MD5 digest */
392         RAND_seed(md, MD_DIGEST_LENGTH);
393         }
394
395     Free(bmbits);
396   }
397
398   /* Select old bitmap back into memory DC */
399   hBitmap = SelectObject(hMemDC, hOldBitmap);
400
401   /* Clean up */
402   DeleteObject(hBitmap);
403   DeleteDC(hMemDC);
404   DeleteDC(hScrDC);
405 }
406 #endif