2 * Copyright (c) 1999, 2000-2001 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
27 Contains: Core routines for the Counterpane Yarrow PRNG.
29 Written by: Counterpane, Inc.
31 Copyright: (c) 2000 by Apple Computer, Inc., all rights reserved.
33 Change History (most recent first):
35 02/10/99 dpm Created, based on Counterpane source.
41 Core routines for the Counterpane PRNG
43 #include "userdefines.h"
44 #include "assertverify.h"
45 #include "dev/random/YarrowCoreLib/include/yarrowUtils.h"
47 #if defined(macintosh) || defined(__APPLE__)
48 /* FIXME - this file needs to be in a platform-independent place */
51 #endif /* macintosh */
54 #include "entropysources.h"
56 #include "dev/random/YarrowCoreLib/include/yarrow.h"
61 #define _MAX(a,b) (((a)>(b))?(a):(b))
62 #define _MIN(a,b) (((a)<(b))?(a):(b))
64 #if defined(macintosh) || defined(__APPLE__)
66 * No mutexes in this module for Macintosh/OSX. We handle the
67 * required locking elsewhere.
69 #define MUTEX_ENABLE 0
71 #include <string.h> /* memcpy, etc. */
72 #if TARGET_API_MAC_OSX
73 #include <sys/time.h> /* for timespec */
74 #elif TARGET_API_MAC_CARBON
75 #include <Timer.h> /* Microseconds */
80 #error Unknown TARGET_API
81 #endif /* TARGET_API */
83 #define MUTEX_ENABLE 1
84 #endif /* macintosh */
87 static HANDLE Statmutex
= NULL
;
88 static DWORD mutexCreatorId
= 0;
92 #pragma mark * * * Static Utility functions * * *
94 /* All error checking should be done in the function that calls these */
97 * out := SHA1(IV | out)
100 prng_do_SHA1(GEN_CTX
*ctx
)
105 SHA1Update(&sha
,ctx
->IV
,20);
106 SHA1Update(&sha
,ctx
->out
,20);
107 SHA1Final(ctx
->out
,&sha
);
115 * Called from init, prngForceReseed(), and prngOutput()
116 * as anti-backtracking mechanism.
119 prng_make_new_state(GEN_CTX
*ctx
,BYTE
*newState
)
123 memcpy(ctx
->IV
,newState
,20);
125 SHA1Update(&sha
,ctx
->IV
,20);
126 SHA1Final(ctx
->out
,&sha
);
134 /* Initialize the secret state with a slow poll */
135 /* Currently only called from prngInitialize */
137 #define SPLEN 65536 /* 64K */
140 prng_slow_init(PRNG
*p
)
141 /* This fails silently and must be fixed. */
143 SHA1_CTX
* ctx
= NULL
;
144 MMPTR mmctx
= MM_NULL
;
146 MMPTR mmbigbuf
= MM_NULL
;
148 MMPTR mmbuf
= MM_NULL
;
151 mmbigbuf
= mmMalloc(SPLEN
);
152 if(mmbigbuf
== MM_NULL
) {goto cleanup_slow_init
;}
153 bigbuf
= (BYTE
*)mmGetPtr(mmbigbuf
);
155 mmbuf
= mmMalloc(20);
156 if(mmbuf
== MM_NULL
) {goto cleanup_slow_init
;}
157 buf
= (BYTE
*)mmGetPtr(mmbuf
);
159 mmctx
= mmMalloc(sizeof(SHA1_CTX
));
160 if(mmctx
== MM_NULL
) {goto cleanup_slow_init
;}
161 ctx
= (SHA1_CTX
*)mmGetPtr(mmctx
);
164 /* Initialize the secret state. */
165 /* Init entropy pool */
167 /* Init output generator */
168 polllength
= prng_slow_poll(bigbuf
,SPLEN
);
170 SHA1Update(ctx
,bigbuf
,polllength
);
172 prng_make_new_state(&p
->outstate
, buf
);
182 #endif /* SLOW_POLL_ENABLE */
184 /* In-place modifed bubble sort */
186 bubbleSort( UINT
*data
, LONG len
)
197 if(data
[i
+1] > data
[i
])
210 #pragma mark * * * Public functions * * *
212 /* Set up the PRNG */
214 prngInitialize(PrngRef
*prng
)
217 comp_error_status resp
;
218 prng_error_status retval
= PRNG_ERR_LOW_MEMORY
;
225 /* Create the mutex */
226 /* NOTE: on return the mutex should bve held, since our caller (prngInitialize)
229 if(mutexCreatorId
!=0) {return PRNG_ERR_REINIT
;}
230 Statmutex
= CreateMutex(NULL
,TRUE
,NULL
);
231 if(Statmutex
== NULL
) {mutexCreatorId
= 0; return PRNG_ERR_MUTEX
;}
232 DuplicateHandle(GetCurrentProcess(),Statmutex
,GetCurrentProcess(),&mutex
,SYNCHRONIZE
,FALSE
,0);
233 mutexCreatorId
= GetCurrentProcessId();
234 #endif /* MUTEX_ENABLE */
237 mmp
= mmMalloc(sizeof(PRNG
));
244 p
= (PRNG
*)mmGetPtr(mmp
);
245 memset(p
, 0, sizeof(PRNG
));
248 /* Initialize Variables */
249 for(i
=0;i
<TOTAL_SOURCES
;i
++)
252 p
->poolEstBits
[i
] = 0;
256 /* Setup security on the registry so that remote users cannot predict the slow pool */
257 prng_set_NT_security();
260 /* Initialize the secret state. */
261 /* FIXME - might want to make this an option here and have the caller
262 * do it after we return....? */
265 prng_slow_init(p
); /* Does a slow poll and then calls prng_make_state(...) */
268 prng_do_SHA1(&p
->outstate
);
269 prng_make_new_state(&p
->outstate
, p
->outstate
.out
);
270 #endif /* SLOW_POLL_ENABLE */
272 /* Initialize compression routines */
273 for(i
=0;i
<COMP_SOURCES
;i
++)
275 resp
= comp_init((p
->comp_state
)+i
);
276 if(resp
!=COMP_SUCCESS
) {retval
= PRNG_ERR_COMPRESSION
; goto cleanup_init
;}
279 p
->ready
= PRNG_READY
;
285 /* Program failed on one of the mmmallocs */
290 CloseHandle(Statmutex
);
295 return retval
; /* default PRNG_ERR_LOW_MEMORY */
300 prngOutput(PRNG
*p
, BYTE
*outbuf
,UINT outbuflen
)
303 GEN_CTX
*ctx
= &p
->outstate
;
308 chASSERT(BACKTRACKLIMIT
> 0);
310 for(i
=0;i
<outbuflen
;i
++,ctx
->index
++,ctx
->numout
++)
312 /* Check backtracklimit */
313 if(ctx
->numout
> BACKTRACKLIMIT
)
316 prng_make_new_state(ctx
, ctx
->out
);
318 /* Check position in IV */
324 outbuf
[i
] = (ctx
->out
)[ctx
->index
];
331 /* Cause the PRNG to reseed now regardless of entropy pool */
332 /* Should this be public? */
334 prngForceReseed(PRNG
*p
, LONGLONG ticks
)
338 FILETIME a
,b
,c
,usertime
;
342 #if defined(macintosh) || defined(__APPLE__)
343 #if (defined(TARGET_API_MAC_OSX) || defined(KERNEL_BUILD))
345 int64_t endTime
, curTime
;
346 #else /* TARGET_API_MAC_CARBON */
347 UnsignedWide uwide
; /* struct needed for Microseconds() */
357 /* Set up start and end times */
358 #if defined(macintosh) || defined(__APPLE__)
359 #if (defined(TARGET_API_MAC_OSX) || defined(KERNEL_BUILD))
360 /* note we can't loop for more than a million microseconds */
364 gettimeofday(&tv
, NULL
);
366 endTime
= (int64_t)tv
.tv_sec
*1000000LL + (int64_t)tv
.tv_usec
+ ticks
;
367 #else /* TARGET_API_MAC_OSX */
368 Microseconds(&uwide
);
369 start
= UnsignedWideToUInt64(uwide
);
370 #endif /* TARGET_API_xxx */
371 #endif /* macintosh */
374 /* Do a couple of iterations between time checks */
375 prngOutput(p
, buf
,64);
376 SHA1Update(&p
->pool
,buf
,64);
377 prngOutput(p
, buf
,64);
378 SHA1Update(&p
->pool
,buf
,64);
379 prngOutput(p
, buf
,64);
380 SHA1Update(&p
->pool
,buf
,64);
381 prngOutput(p
, buf
,64);
382 SHA1Update(&p
->pool
,buf
,64);
383 prngOutput(p
, buf
,64);
384 SHA1Update(&p
->pool
,buf
,64);
386 #if defined(macintosh) || defined(__APPLE__)
387 #if defined(TARGET_API_MAC_OSX) || defined(KERNEL_BUILD)
388 #ifdef TARGET_API_MAC_OSX
389 gettimeofday(&tv
, NULL
);
392 curTime
= (int64_t)tv
.tv_sec
*1000000LL + (int64_t)tv
.tv_usec
;
394 } while(curTime
< endTime
);
396 Microseconds(&uwide
);
397 now
= UnsignedWideToUInt64(uwide
);
398 } while ( (now
-start
) < ticks
) ;
401 } while ( (now
-start
) < ticks
) ;
403 SHA1Final(dig
,&p
->pool
);
404 SHA1Update(&p
->pool
,dig
,20);
405 SHA1Final(dig
,&p
->pool
);
407 /* Reset secret state */
409 prng_make_new_state(&p
->outstate
,dig
);
411 /* Clear counter variables */
412 for(i
=0;i
<TOTAL_SOURCES
;i
++)
415 p
->poolEstBits
[i
] = 0;
419 trashMemory(dig
,20*sizeof(char));
420 trashMemory(buf
,64*sizeof(char));
426 /* Input a state into the PRNG */
428 prngProcessSeedBuffer(PRNG
*p
, BYTE
*buf
,LONGLONG ticks
)
434 /* Put the data into the entropy, add some data from the unknown state, reseed */
435 SHA1Update(&p
->pool
,buf
,20); /* Put it into the entropy pool */
436 prng_do_SHA1(&p
->outstate
); /* Output 20 more bytes and */
437 SHA1Update(&p
->pool
,p
->outstate
.out
,20);/* add it to the pool as well. */
438 prngForceReseed(p
, ticks
); /* Do a reseed */
439 return prngOutput(p
, buf
,20); /* Return the first 20 bytes of output in buf */
443 /* Take some "random" data and make more "random-looking" data from it */
444 /* note: this routine has no context, no mutex wrapper */
446 prngStretch(BYTE
*inbuf
,UINT inbuflen
,BYTE
*outbuf
,UINT outbuflen
) {
454 if(inbuflen
>= outbuflen
)
456 memcpy(outbuf
,inbuf
,outbuflen
);
459 else /* Extend using SHA1 hash of inbuf */
462 SHA1Update(&ctx
,inbuf
,inbuflen
);
464 for(prev
=0,left
=outbuflen
;left
>0;prev
+=20,left
-=20)
466 SHA1Update(&ctx
,dig
,20);
468 memcpy(outbuf
+prev
,dig
,(left
>20)?20:left
);
470 trashMemory(dig
,20*sizeof(BYTE
));
475 return PRNG_ERR_PROGRAM_FLOW
;
479 /* Add entropy to the PRNG from a source */
481 prngInput(PRNG
*p
, BYTE
*inbuf
,UINT inbuflen
,UINT poolnum
, __unused UINT estbits
)
483 #ifndef YARROW_KERNEL
484 comp_error_status resp
;
490 if(poolnum
>= TOTAL_SOURCES
) {return PRNG_ERR_OUT_OF_BOUNDS
;}
492 /* Add to entropy pool */
493 SHA1Update(&p
->pool
,inbuf
,inbuflen
);
495 #ifndef YARROW_KERNEL
496 /* skip this step for the kernel */
498 /* Update pool size, pool user estimate and pool compression context */
499 p
->poolSize
[poolnum
] += inbuflen
;
500 p
->poolEstBits
[poolnum
] += estbits
;
501 if(poolnum
<COMP_SOURCES
)
503 resp
= comp_add_data((p
->comp_state
)+poolnum
,inbuf
,inbuflen
);
504 if(resp
!=COMP_SUCCESS
) {return PRNG_ERR_COMPRESSION
;}
506 #endif /* YARROW_KERNEL */
513 /* If we have enough entropy, allow a reseed of the system */
515 prngAllowReseed(PRNG
*p
, LONGLONG ticks
)
517 UINT temp
[TOTAL_SOURCES
];
525 comp_error_status resp
;
530 for(i
=0;i
<ENTROPY_SOURCES
;i
++)
532 /* Make sure that compression-based entropy estimates are current */
533 #ifndef KERNEL_BUILD // floating point in a kernel is BAD!
534 resp
= comp_get_ratio((p
->comp_state
)+i
,&ratio
);
535 if(resp
!=COMP_SUCCESS
) {return PRNG_ERR_COMPRESSION
;}
536 /* Use 4 instead of 8 to half compression estimate */
537 temp
[i
] = (int)(ratio
*p
->poolSize
[i
]*4);
539 temp
[i
] = p
->poolSize
[i
] * 4;
543 /* Use minumum of user and compression estimate for compressed sources */
544 for(i
=ENTROPY_SOURCES
;i
<COMP_SOURCES
;i
++)
547 /* Make sure that compression-based entropy estimates are current */
548 resp
= comp_get_ratio((p
->comp_state
)+i
,&ratio
);
549 if(resp
!=COMP_SUCCESS
) {return PRNG_ERR_COMPRESSION
;}
550 /* Use 4 instead of 8 to half compression estimate */
551 temp
[i
] = _MIN((int)(ratio
*p
->poolSize
[i
]*4),(int)p
->poolEstBits
[i
]);
553 temp
[i
] = _MIN (p
->poolSize
[i
] * 4, p
->poolEstBits
[i
]);
557 /* Use user estimate for remaining sources */
558 for(i
=COMP_SOURCES
;i
<TOTAL_SOURCES
;i
++) {temp
[i
] = p
->poolEstBits
[i
];}
561 /* pointless if we're not ignoring any sources */
562 bubbleSort(temp
,TOTAL_SOURCES
);
564 for(i
=K
,sum
=0;i
<TOTAL_SOURCES
;sum
+=temp
[i
++]); /* Stupid C trick */
566 return prngForceReseed(p
, ticks
);
568 return PRNG_ERR_NOT_ENOUGH_ENTROPY
;
570 return PRNG_ERR_PROGRAM_FLOW
;
574 /* Call a slow poll and insert the data into the entropy pool */
575 static prng_error_status
576 prngSlowPoll(PRNG
*p
, UINT pollsize
)
580 prng_error_status retval
;
584 buf
= (BYTE
*)malloc(pollsize
);
585 if(buf
==NULL
) {return PRNG_ERR_LOW_MEMORY
;}
586 len
= prng_slow_poll(buf
,pollsize
); /* OS specific call */
587 retval
= prngInput(p
, buf
,len
,SLOWPOLLSOURCE
, len
* 8);
588 trashMemory(buf
,pollsize
);
593 #endif /* SLOW_POLL_ENABLE */
596 /* Delete the PRNG */
603 if(GetCurrentProcessId()!=mutexCreatorId
) {return PRNG_ERR_WRONG_CALLER
;}
605 if(p
==NULL
) {return PRNG_SUCCESS
;} /* Well, there is nothing to destroy... */
607 p
->ready
= PRNG_NOT_READY
;
609 for(i
=0;i
<COMP_SOURCES
;i
++)
611 comp_end((p
->comp_state
)+i
);
615 CloseHandle(Statmutex
);