2 * Copyright (c) 1999, 2000-2001 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
8 * This file contains Original Code and/or Modifications of Original Code
9 * as defined in and that are subject to the Apple Public Source License
10 * Version 2.0 (the 'License'). You may not use this file except in
11 * compliance with the License. Please obtain a copy of the License at
12 * http://www.opensource.apple.com/apsl/ and read it before using this
15 * The Original Code and all software distributed under the License are
16 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
17 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
20 * Please see the License for the specific language governing rights and
21 * limitations under the License.
23 * @APPLE_LICENSE_HEADER_END@
29 Contains: Core routines for the Counterpane Yarrow PRNG.
31 Written by: Counterpane, Inc.
33 Copyright: (c) 2000 by Apple Computer, Inc., all rights reserved.
35 Change History (most recent first):
37 02/10/99 dpm Created, based on Counterpane source.
43 Core routines for the Counterpane PRNG
45 #include "userdefines.h"
46 #include "assertverify.h"
47 #include "dev/random/YarrowCoreLib/include/yarrowUtils.h"
49 #if defined(macintosh) || defined(__APPLE__)
50 /* FIXME - this file needs to be in a platform-independent place */
53 #endif /* macintosh */
56 #include "entropysources.h"
58 #include "dev/random/YarrowCoreLib/include/yarrow.h"
63 #define _MAX(a,b) (((a)>(b))?(a):(b))
64 #define _MIN(a,b) (((a)<(b))?(a):(b))
66 #if defined(macintosh) || defined(__APPLE__)
68 * No mutexes in this module for Macintosh/OSX. We handle the
69 * required locking elsewhere.
71 #define MUTEX_ENABLE 0
73 #include <string.h> /* memcpy, etc. */
74 #if TARGET_API_MAC_OSX
75 #include <sys/time.h> /* for timespec */
76 #elif TARGET_API_MAC_CARBON
77 #include <Timer.h> /* Microseconds */
82 #error Unknown TARGET_API
83 #endif /* TARGET_API */
85 #define MUTEX_ENABLE 1
86 #endif /* macintosh */
89 static HANDLE Statmutex
= NULL
;
90 static DWORD mutexCreatorId
= 0;
94 #pragma mark * * * Static Utility functions * * *
96 /* All error checking should be done in the function that calls these */
99 * out := SHA1(IV | out)
102 prng_do_SHA1(GEN_CTX
*ctx
)
107 SHA1Update(&sha
,ctx
->IV
,20);
108 SHA1Update(&sha
,ctx
->out
,20);
109 SHA1Final(ctx
->out
,&sha
);
117 * Called from init, prngForceReseed(), and prngOutput()
118 * as anti-backtracking mechanism.
121 prng_make_new_state(GEN_CTX
*ctx
,BYTE
*newState
)
125 memcpy(ctx
->IV
,newState
,20);
127 SHA1Update(&sha
,ctx
->IV
,20);
128 SHA1Final(ctx
->out
,&sha
);
136 /* Initialize the secret state with a slow poll */
137 /* Currently only called from prngInitialize */
139 #define SPLEN 65536 /* 64K */
142 prng_slow_init(PRNG
*p
)
143 /* This fails silently and must be fixed. */
145 SHA1_CTX
* ctx
= NULL
;
146 MMPTR mmctx
= MM_NULL
;
148 MMPTR mmbigbuf
= MM_NULL
;
150 MMPTR mmbuf
= MM_NULL
;
153 mmbigbuf
= mmMalloc(SPLEN
);
154 if(mmbigbuf
== MM_NULL
) {goto cleanup_slow_init
;}
155 bigbuf
= (BYTE
*)mmGetPtr(mmbigbuf
);
157 mmbuf
= mmMalloc(20);
158 if(mmbuf
== MM_NULL
) {goto cleanup_slow_init
;}
159 buf
= (BYTE
*)mmGetPtr(mmbuf
);
161 mmctx
= mmMalloc(sizeof(SHA1_CTX
));
162 if(mmctx
== MM_NULL
) {goto cleanup_slow_init
;}
163 ctx
= (SHA1_CTX
*)mmGetPtr(mmctx
);
166 /* Initialize the secret state. */
167 /* Init entropy pool */
169 /* Init output generator */
170 polllength
= prng_slow_poll(bigbuf
,SPLEN
);
172 SHA1Update(ctx
,bigbuf
,polllength
);
174 prng_make_new_state(&p
->outstate
, buf
);
184 #endif /* SLOW_POLL_ENABLE */
186 /* In-place modifed bubble sort */
188 bubbleSort(UINT
*data
,UINT len
)
190 UINT i
,last
,newlast
,temp
;
198 if(data
[i
+1] > data
[i
])
211 #pragma mark * * * Public functions * * *
213 /* Set up the PRNG */
215 prngInitialize(PrngRef
*prng
)
218 comp_error_status resp
;
219 prng_error_status retval
= PRNG_ERR_LOW_MEMORY
;
226 /* Create the mutex */
227 /* NOTE: on return the mutex should bve held, since our caller (prngInitialize)
230 if(mutexCreatorId
!=0) {return PRNG_ERR_REINIT
;}
231 Statmutex
= CreateMutex(NULL
,TRUE
,NULL
);
232 if(Statmutex
== NULL
) {mutexCreatorId
= 0; return PRNG_ERR_MUTEX
;}
233 DuplicateHandle(GetCurrentProcess(),Statmutex
,GetCurrentProcess(),&mutex
,SYNCHRONIZE
,FALSE
,0);
234 mutexCreatorId
= GetCurrentProcessId();
235 #endif /* MUTEX_ENABLE */
238 mmp
= mmMalloc(sizeof(PRNG
));
245 p
= (PRNG
*)mmGetPtr(mmp
);
246 memset(p
, 0, sizeof(PRNG
));
249 /* Initialize Variables */
250 for(i
=0;i
<TOTAL_SOURCES
;i
++)
253 p
->poolEstBits
[i
] = 0;
257 /* Setup security on the registry so that remote users cannot predict the slow pool */
258 prng_set_NT_security();
261 /* Initialize the secret state. */
262 /* FIXME - might want to make this an option here and have the caller
263 * do it after we return....? */
266 prng_slow_init(p
); /* Does a slow poll and then calls prng_make_state(...) */
269 prng_do_SHA1(&p
->outstate
);
270 prng_make_new_state(&p
->outstate
, p
->outstate
.out
);
271 #endif /* SLOW_POLL_ENABLE */
273 /* Initialize compression routines */
274 for(i
=0;i
<COMP_SOURCES
;i
++)
276 resp
= comp_init((p
->comp_state
)+i
);
277 if(resp
!=COMP_SUCCESS
) {retval
= PRNG_ERR_COMPRESSION
; goto cleanup_init
;}
280 p
->ready
= PRNG_READY
;
286 /* Program failed on one of the mmmallocs */
291 CloseHandle(Statmutex
);
296 return retval
; /* default PRNG_ERR_LOW_MEMORY */
301 prngOutput(PRNG
*p
, BYTE
*outbuf
,UINT outbuflen
)
304 GEN_CTX
*ctx
= &p
->outstate
;
309 chASSERT(BACKTRACKLIMIT
> 0);
311 for(i
=0;i
<outbuflen
;i
++,ctx
->index
++,ctx
->numout
++)
313 /* Check backtracklimit */
314 if(ctx
->numout
> BACKTRACKLIMIT
)
317 prng_make_new_state(ctx
, ctx
->out
);
319 /* Check position in IV */
325 outbuf
[i
] = (ctx
->out
)[ctx
->index
];
332 /* Cause the PRNG to reseed now regardless of entropy pool */
333 /* Should this be public? */
335 prngForceReseed(PRNG
*p
, LONGLONG ticks
)
339 FILETIME a
,b
,c
,usertime
;
343 #if defined(macintosh) || defined(__APPLE__)
344 #if (defined(TARGET_API_MAC_OSX) || defined(KERNEL_BUILD))
347 #else TARGET_API_MAC_CARBON
348 UnsignedWide uwide
; /* struct needed for Microseconds() */
358 /* Set up start and end times */
359 #if defined(macintosh) || defined(__APPLE__)
360 #if (defined(TARGET_API_MAC_OSX) || defined(KERNEL_BUILD))
361 /* note we can't loop for more than a million microseconds */
365 gettimeofday(&tv
, NULL
);
367 endTime
= tv
.tv_usec
+ ticks
;
368 if(endTime
> 1000000) {
369 /* handle rollover now */
372 #else /* TARGET_API_MAC_OSX */
373 Microseconds(&uwide
);
374 start
= UnsignedWideToUInt64(uwide
);
375 #endif /* TARGET_API_xxx */
376 #endif /* macintosh */
379 /* Do a couple of iterations between time checks */
380 prngOutput(p
, buf
,64);
381 SHA1Update(&p
->pool
,buf
,64);
382 prngOutput(p
, buf
,64);
383 SHA1Update(&p
->pool
,buf
,64);
384 prngOutput(p
, buf
,64);
385 SHA1Update(&p
->pool
,buf
,64);
386 prngOutput(p
, buf
,64);
387 SHA1Update(&p
->pool
,buf
,64);
388 prngOutput(p
, buf
,64);
389 SHA1Update(&p
->pool
,buf
,64);
391 #if defined(macintosh) || defined(__APPLE__)
392 #if defined(TARGET_API_MAC_OSX) || defined(KERNEL_BUILD)
393 #ifdef TARGET_API_MAC_OSX
394 gettimeofday(&tv
, NULL
);
398 } while(tv
.tv_usec
< endTime
);
400 Microseconds(&uwide
);
401 now
= UnsignedWideToUInt64(uwide
);
402 } while ( (now
-start
) < ticks
) ;
405 } while ( (now
-start
) < ticks
) ;
407 SHA1Final(dig
,&p
->pool
);
408 SHA1Update(&p
->pool
,dig
,20);
409 SHA1Final(dig
,&p
->pool
);
411 /* Reset secret state */
413 prng_make_new_state(&p
->outstate
,dig
);
415 /* Clear counter variables */
416 for(i
=0;i
<TOTAL_SOURCES
;i
++)
419 p
->poolEstBits
[i
] = 0;
423 trashMemory(dig
,20*sizeof(char));
424 trashMemory(buf
,64*sizeof(char));
430 /* Input a state into the PRNG */
432 prngProcessSeedBuffer(PRNG
*p
, BYTE
*buf
,LONGLONG ticks
)
438 /* Put the data into the entropy, add some data from the unknown state, reseed */
439 SHA1Update(&p
->pool
,buf
,20); /* Put it into the entropy pool */
440 prng_do_SHA1(&p
->outstate
); /* Output 20 more bytes and */
441 SHA1Update(&p
->pool
,p
->outstate
.out
,20);/* add it to the pool as well. */
442 prngForceReseed(p
, ticks
); /* Do a reseed */
443 return prngOutput(p
, buf
,20); /* Return the first 20 bytes of output in buf */
447 /* Take some "random" data and make more "random-looking" data from it */
448 /* note: this routine has no context, no mutex wrapper */
450 prngStretch(BYTE
*inbuf
,UINT inbuflen
,BYTE
*outbuf
,UINT outbuflen
) {
458 if(inbuflen
>= outbuflen
)
460 memcpy(outbuf
,inbuf
,outbuflen
);
463 else /* Extend using SHA1 hash of inbuf */
466 SHA1Update(&ctx
,inbuf
,inbuflen
);
468 for(prev
=0,left
=outbuflen
;left
>0;prev
+=20,left
-=20)
470 SHA1Update(&ctx
,dig
,20);
472 memcpy(outbuf
+prev
,dig
,(left
>20)?20:left
);
474 trashMemory(dig
,20*sizeof(BYTE
));
479 return PRNG_ERR_PROGRAM_FLOW
;
483 /* Add entropy to the PRNG from a source */
485 prngInput(PRNG
*p
, BYTE
*inbuf
,UINT inbuflen
,UINT poolnum
,UINT estbits
)
487 #ifndef YARROW_KERNEL
488 comp_error_status resp
;
494 if(poolnum
>= TOTAL_SOURCES
) {return PRNG_ERR_OUT_OF_BOUNDS
;}
496 /* Add to entropy pool */
497 SHA1Update(&p
->pool
,inbuf
,inbuflen
);
499 #ifndef YARROW_KERNEL
500 /* skip this step for the kernel */
502 /* Update pool size, pool user estimate and pool compression context */
503 p
->poolSize
[poolnum
] += inbuflen
;
504 p
->poolEstBits
[poolnum
] += estbits
;
505 if(poolnum
<COMP_SOURCES
)
507 resp
= comp_add_data((p
->comp_state
)+poolnum
,inbuf
,inbuflen
);
508 if(resp
!=COMP_SUCCESS
) {return PRNG_ERR_COMPRESSION
;}
510 #endif /* YARROW_KERNEL */
517 /* If we have enough entropy, allow a reseed of the system */
519 prngAllowReseed(PRNG
*p
, LONGLONG ticks
)
521 UINT temp
[TOTAL_SOURCES
];
527 comp_error_status resp
;
532 for(i
=0;i
<ENTROPY_SOURCES
;i
++)
534 /* Make sure that compression-based entropy estimates are current */
535 #ifndef KERNEL_BUILD // floating point in a kernel is BAD!
536 resp
= comp_get_ratio((p
->comp_state
)+i
,&ratio
);
537 if(resp
!=COMP_SUCCESS
) {return PRNG_ERR_COMPRESSION
;}
538 /* Use 4 instead of 8 to half compression estimate */
539 temp
[i
] = (int)(ratio
*p
->poolSize
[i
]*4);
541 temp
[i
] = p
->poolSize
[i
] * 4;
545 /* Use minumum of user and compression estimate for compressed sources */
546 for(i
=ENTROPY_SOURCES
;i
<COMP_SOURCES
;i
++)
549 /* Make sure that compression-based entropy estimates are current */
550 resp
= comp_get_ratio((p
->comp_state
)+i
,&ratio
);
551 if(resp
!=COMP_SUCCESS
) {return PRNG_ERR_COMPRESSION
;}
552 /* Use 4 instead of 8 to half compression estimate */
553 temp
[i
] = _MIN((int)(ratio
*p
->poolSize
[i
]*4),(int)p
->poolEstBits
[i
]);
555 temp
[i
] = _MIN (p
->poolSize
[i
] * 4, p
->poolEstBits
[i
]);
559 /* Use user estimate for remaining sources */
560 for(i
=COMP_SOURCES
;i
<TOTAL_SOURCES
;i
++) {temp
[i
] = p
->poolEstBits
[i
];}
563 /* pointless if we're not ignoring any sources */
564 bubbleSort(temp
,TOTAL_SOURCES
);
566 for(i
=K
,sum
=0;i
<TOTAL_SOURCES
;sum
+=temp
[i
++]); /* Stupid C trick */
568 return prngForceReseed(p
, ticks
);
570 return PRNG_ERR_NOT_ENOUGH_ENTROPY
;
572 return PRNG_ERR_PROGRAM_FLOW
;
576 /* Call a slow poll and insert the data into the entropy pool */
577 static prng_error_status
578 prngSlowPoll(PRNG
*p
, UINT pollsize
)
582 prng_error_status retval
;
586 buf
= (BYTE
*)malloc(pollsize
);
587 if(buf
==NULL
) {return PRNG_ERR_LOW_MEMORY
;}
588 len
= prng_slow_poll(buf
,pollsize
); /* OS specific call */
589 retval
= prngInput(p
, buf
,len
,SLOWPOLLSOURCE
, len
* 8);
590 trashMemory(buf
,pollsize
);
595 #endif /* SLOW_POLL_ENABLE */
598 /* Delete the PRNG */
605 if(GetCurrentProcessId()!=mutexCreatorId
) {return PRNG_ERR_WRONG_CALLER
;}
607 if(p
==NULL
) {return PRNG_SUCCESS
;} /* Well, there is nothing to destroy... */
609 p
->ready
= PRNG_NOT_READY
;
611 for(i
=0;i
<COMP_SOURCES
;i
++)
613 comp_end((p
->comp_state
)+i
);
617 CloseHandle(Statmutex
);