080581afcdc028d5421ad978876b39fa9a77c8cd
[openssl.git] / crypto / rand / md_rand.c
1 /* crypto/rand/md_rand.c */
2 /* Copyright (C) 1995-1998 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 <sys/types.h>
61 #include <time.h>
62 #include <string.h>
63
64 #ifndef FLAT_INC
65 # include "../../e_os.h"
66 #else
67 # include "e_os.h"
68 #endif
69
70 #include <openssl/crypto.h>
71
72 #if !defined(USE_MD5_RAND) && !defined(USE_SHA1_RAND) && !defined(USE_MDC2_RAND) && !defined(USE_MD2_RAND)
73 #if !defined(NO_SHA) && !defined(NO_SHA1)
74 #define USE_SHA1_RAND
75 #elif !defined(NO_MD5)
76 #define USE_MD5_RAND
77 #elif !defined(NO_MDC2) && !defined(NO_DES)
78 #define USE_MDC2_RAND
79 #elif !defined(NO_MD2)
80 #define USE_MD2_RAND
81 #else
82 #error No message digest algorithm available
83 #endif
84 #endif
85
86 /* Changed how the state buffer used.  I now attempt to 'wrap' such
87  * that I don't run over the same locations the next time  go through
88  * the 1023 bytes - many thanks to
89  * Robert J. LeBlanc <rjl@renaissoft.com> for his comments
90  */
91
92 #if defined(USE_MD5_RAND)
93 #include <openssl/md5.h>
94 #define MD_DIGEST_LENGTH        MD5_DIGEST_LENGTH
95 #define MD_CTX                  MD5_CTX
96 #define MD_Init(a)              MD5_Init(a)
97 #define MD_Update(a,b,c)        MD5_Update(a,b,c)
98 #define MD_Final(a,b)           MD5_Final(a,b)
99 #define MD(a,b,c)               MD5(a,b,c)
100 #elif defined(USE_SHA1_RAND)
101 #include <openssl/sha.h>
102 #define MD_DIGEST_LENGTH        SHA_DIGEST_LENGTH
103 #define MD_CTX                  SHA_CTX
104 #define MD_Init(a)              SHA1_Init(a)
105 #define MD_Update(a,b,c)        SHA1_Update(a,b,c)
106 #define MD_Final(a,b)           SHA1_Final(a,b)
107 #define MD(a,b,c)               SHA1(a,b,c)
108 #elif defined(USE_MDC2_RAND)
109 #include <openssl/mdc2.h>
110 #define MD_DIGEST_LENGTH        MDC2_DIGEST_LENGTH
111 #define MD_CTX                  MDC2_CTX
112 #define MD_Init(a)              MDC2_Init(a)
113 #define MD_Update(a,b,c)        MDC2_Update(a,b,c)
114 #define MD_Final(a,b)           MDC2_Final(a,b)
115 #define MD(a,b,c)               MDC2(a,b,c)
116 #elif defined(USE_MD2_RAND)
117 #include <openssl/md2.h>
118 #define MD_DIGEST_LENGTH        MD2_DIGEST_LENGTH
119 #define MD_CTX                  MD2_CTX
120 #define MD_Init(a)              MD2_Init(a)
121 #define MD_Update(a,b,c)        MD2_Update(a,b,c)
122 #define MD_Final(a,b)           MD2_Final(a,b)
123 #define MD(a,b,c)               MD2(a,b,c)
124 #endif
125
126 #include <openssl/rand.h>
127
128 /* #define NORAND       1 */
129 /* #define PREDICT      1 */
130
131 #define STATE_SIZE      1023
132 static int state_num=0,state_index=0;
133 static unsigned char state[STATE_SIZE+MD_DIGEST_LENGTH];
134 static unsigned char md[MD_DIGEST_LENGTH];
135 static long md_count[2]={0,0};
136
137 const char *RAND_version="RAND" OPENSSL_VERSION_PTEXT;
138
139 static void ssleay_rand_cleanup(void);
140 static void ssleay_rand_seed(const void *buf, int num);
141 static void ssleay_rand_bytes(unsigned char *buf, int num);
142
143 RAND_METHOD rand_ssleay_meth={
144         ssleay_rand_seed,
145         ssleay_rand_bytes,
146         ssleay_rand_cleanup,
147         }; 
148
149 RAND_METHOD *RAND_SSLeay(void)
150         {
151         return(&rand_ssleay_meth);
152         }
153
154 static void ssleay_rand_cleanup(void)
155         {
156         memset(state,0,sizeof(state));
157         state_num=0;
158         state_index=0;
159         memset(md,0,MD_DIGEST_LENGTH);
160         md_count[0]=0;
161         md_count[1]=0;
162         }
163
164 static void ssleay_rand_seed(const void *buf, int num)
165         {
166         int i,j,k,st_idx,st_num;
167         MD_CTX m;
168
169 #ifdef NORAND
170         return;
171 #endif
172
173         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
174         st_idx=state_index;
175         st_num=state_num;
176
177         state_index=(state_index+num);
178         if (state_index >= STATE_SIZE)
179                 {
180                 state_index%=STATE_SIZE;
181                 state_num=STATE_SIZE;
182                 }
183         else if (state_num < STATE_SIZE)        
184                 {
185                 if (state_index > state_num)
186                         state_num=state_index;
187                 }
188         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
189
190         for (i=0; i<num; i+=MD_DIGEST_LENGTH)
191                 {
192                 j=(num-i);
193                 j=(j > MD_DIGEST_LENGTH)?MD_DIGEST_LENGTH:j;
194
195                 MD_Init(&m);
196                 MD_Update(&m,md,MD_DIGEST_LENGTH);
197                 k=(st_idx+j)-STATE_SIZE;
198                 if (k > 0)
199                         {
200                         MD_Update(&m,&(state[st_idx]),j-k);
201                         MD_Update(&m,&(state[0]),k);
202                         }
203                 else
204                         MD_Update(&m,&(state[st_idx]),j);
205                         
206                 MD_Update(&m,buf,j);
207                 MD_Update(&m,(unsigned char *)&(md_count[0]),sizeof(md_count));
208                 MD_Final(md,&m);
209                 md_count[1]++;
210
211                 buf=(const char *)buf + j;
212
213                 for (k=0; k<j; k++)
214                         {
215                         state[st_idx++]^=md[k];
216                         if (st_idx >= STATE_SIZE)
217                                 {
218                                 st_idx=0;
219                                 st_num=STATE_SIZE;
220                                 }
221                         }
222                 }
223         memset((char *)&m,0,sizeof(m));
224         }
225
226 static void ssleay_rand_bytes(unsigned char *buf, int num)
227         {
228         int i,j,k,st_num,st_idx;
229         MD_CTX m;
230         static int init=1;
231         unsigned long l;
232 #ifdef DEVRANDOM
233         FILE *fh;
234 #endif
235
236 #ifdef PREDICT
237         {
238         static unsigned char val=0;
239
240         for (i=0; i<num; i++)
241                 buf[i]=val++;
242         return;
243         }
244 #endif
245
246         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
247
248         if (init)
249                 {
250                 CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
251                 /* put in some default random data, we need more than
252                  * just this */
253                 RAND_seed(&m,sizeof(m));
254 #ifndef MSDOS
255                 l=getpid();
256                 RAND_seed(&l,sizeof(l));
257                 l=getuid();
258                 RAND_seed(&l,sizeof(l));
259 #endif
260                 l=time(NULL);
261                 RAND_seed(&l,sizeof(l));
262
263 /* #ifdef DEVRANDOM */
264                 /* 
265                  * Use a random entropy pool device.
266                  * Linux 1.3.x and FreeBSD-Current has 
267                  * this. Use /dev/urandom if you can
268                  * as /dev/random will block if it runs out
269                  * of random entries.
270                  */
271                 if ((fh = fopen(DEVRANDOM, "r")) != NULL)
272                         {
273                         unsigned char tmpbuf[32];
274
275                         fread((unsigned char *)tmpbuf,1,32,fh);
276                         /* we don't care how many bytes we read,
277                          * we will just copy the 'stack' if there is
278                          * nothing else :-) */
279                         fclose(fh);
280                         RAND_seed(tmpbuf,32);
281                         memset(tmpbuf,0,32);
282                         }
283 /* #endif */
284 #ifdef PURIFY
285                 memset(state,0,STATE_SIZE);
286                 memset(md,0,MD_DIGEST_LENGTH);
287 #endif
288                 CRYPTO_w_lock(CRYPTO_LOCK_RAND);
289                 init=0;
290                 }
291
292         st_idx=state_index;
293         st_num=state_num;
294         state_index+=num;
295         if (state_index > state_num)
296                 state_index=(state_index%state_num);
297
298         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
299
300         while (num > 0)
301                 {
302                 j=(num >= MD_DIGEST_LENGTH/2)?MD_DIGEST_LENGTH/2:num;
303                 num-=j;
304                 MD_Init(&m);
305                 MD_Update(&m,&(md[MD_DIGEST_LENGTH/2]),MD_DIGEST_LENGTH/2);
306                 MD_Update(&m,(unsigned char *)&(md_count[0]),sizeof(md_count));
307 #ifndef PURIFY
308                 MD_Update(&m,buf,j); /* purify complains */
309 #endif
310                 k=(st_idx+j)-st_num;
311                 if (k > 0)
312                         {
313                         MD_Update(&m,&(state[st_idx]),j-k);
314                         MD_Update(&m,&(state[0]),k);
315                         }
316                 else
317                         MD_Update(&m,&(state[st_idx]),j);
318                 MD_Final(md,&m);
319
320                 for (i=0; i<j; i++)
321                         {
322                         if (st_idx >= st_num)
323                                 st_idx=0;
324                         state[st_idx++]^=md[i];
325                         *(buf++)=md[i+MD_DIGEST_LENGTH/2];
326                         }
327                 }
328
329         MD_Init(&m);
330         MD_Update(&m,(unsigned char *)&(md_count[0]),sizeof(md_count));
331         md_count[0]++;
332         MD_Update(&m,md,MD_DIGEST_LENGTH);
333         MD_Final(md,&m);
334         memset(&m,0,sizeof(m));
335         }
336
337 #ifdef WINDOWS
338 #include <windows.h>
339 #include <openssl/rand.h>
340
341 /*****************************************************************************
342  * Initialisation function for the SSL random generator.  Takes the contents
343  * of the screen as random seed.
344  *
345  * Created 960901 by Gertjan van Oosten, gertjan@West.NL, West Consulting B.V.
346  *
347  * Code adapted from
348  * <URL:http://www.microsoft.com/kb/developr/win_dk/q97193.htm>;
349  * the original copyright message is:
350  *
351  *   (C) Copyright Microsoft Corp. 1993.  All rights reserved.
352  *
353  *   You have a royalty-free right to use, modify, reproduce and
354  *   distribute the Sample Files (and/or any modified version) in
355  *   any way you find useful, provided that you agree that
356  *   Microsoft has no warranty obligations or liability for any
357  *   Sample Application Files which are modified.
358  */
359 /*
360  * I have modified the loading of bytes via RAND_seed() mechanism since
361  * the origional would have been very very CPU intensive since RAND_seed()
362  * does an MD5 per 16 bytes of input.  The cost to digest 16 bytes is the same
363  * as that to digest 56 bytes.  So under the old system, a screen of
364  * 1024*768*256 would have been CPU cost of approximatly 49,000 56 byte MD5
365  * digests or digesting 2.7 mbytes.  What I have put in place would
366  * be 48 16k MD5 digests, or efectivly 48*16+48 MD5 bytes or 816 kbytes
367  * or about 3.5 times as much.
368  * - eric 
369  */
370 void RAND_screen(void)
371 {
372   HDC           hScrDC;         /* screen DC */
373   HDC           hMemDC;         /* memory DC */
374   HBITMAP       hBitmap;        /* handle for our bitmap */
375   HBITMAP       hOldBitmap;     /* handle for previous bitmap */
376   BITMAP        bm;             /* bitmap properties */
377   unsigned int  size;           /* size of bitmap */
378   char          *bmbits;        /* contents of bitmap */
379   int           w;              /* screen width */
380   int           h;              /* screen height */
381   int           y;              /* y-coordinate of screen lines to grab */
382   int           n = 16;         /* number of screen lines to grab at a time */
383
384   /* Create a screen DC and a memory DC compatible to screen DC */
385   hScrDC = CreateDC("DISPLAY", NULL, NULL, NULL);
386   hMemDC = CreateCompatibleDC(hScrDC);
387
388   /* Get screen resolution */
389   w = GetDeviceCaps(hScrDC, HORZRES);
390   h = GetDeviceCaps(hScrDC, VERTRES);
391
392   /* Create a bitmap compatible with the screen DC */
393   hBitmap = CreateCompatibleBitmap(hScrDC, w, n);
394
395   /* Select new bitmap into memory DC */
396   hOldBitmap = SelectObject(hMemDC, hBitmap);
397
398   /* Get bitmap properties */
399   GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&bm);
400   size = (unsigned int)bm.bmWidthBytes * bm.bmHeight * bm.bmPlanes;
401
402   bmbits = Malloc(size);
403   if (bmbits) {
404     /* Now go through the whole screen, repeatedly grabbing n lines */
405     for (y = 0; y < h-n; y += n)
406         {
407         unsigned char md[MD_DIGEST_LENGTH];
408
409         /* Bitblt screen DC to memory DC */
410         BitBlt(hMemDC, 0, 0, w, n, hScrDC, 0, y, SRCCOPY);
411
412         /* Copy bitmap bits from memory DC to bmbits */
413         GetBitmapBits(hBitmap, size, bmbits);
414
415         /* Get the MD5 of the bitmap */
416         MD(bmbits,size,md);
417
418         /* Seed the random generator with the MD5 digest */
419         RAND_seed(md, MD_DIGEST_LENGTH);
420         }
421
422     Free(bmbits);
423   }
424
425   /* Select old bitmap back into memory DC */
426   hBitmap = SelectObject(hMemDC, hOldBitmap);
427
428   /* Clean up */
429   DeleteObject(hBitmap);
430   DeleteDC(hMemDC);
431   DeleteDC(hScrDC);
432 }
433 #endif