2 * Copyright (c) 1999, 2000-2001 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
20 * @APPLE_LICENSE_HEADER_END@
26 Contains: Core routines for the Counterpane Yarrow PRNG.
28 Written by: Counterpane, Inc.
30 Copyright: (c) 2000 by Apple Computer, Inc., all rights reserved.
32 Change History (most recent first):
34 02/10/99 dpm Created, based on Counterpane source.
40 Core routines for the Counterpane PRNG
42 #include "userdefines.h"
43 #include "assertverify.h"
44 #include "dev/random/YarrowCoreLib/include/yarrowUtils.h"
46 #if defined(macintosh) || defined(__APPLE__)
47 /* FIXME - this file needs to be in a platform-independent place */
50 #endif /* macintosh */
53 #include "entropysources.h"
55 #include "dev/random/YarrowCoreLib/include/yarrow.h"
60 #define _MAX(a,b) (((a)>(b))?(a):(b))
61 #define _MIN(a,b) (((a)<(b))?(a):(b))
63 #if defined(macintosh) || defined(__APPLE__)
65 * No mutexes in this module for Macintosh/OSX. We handle the
66 * required locking elsewhere.
68 #define MUTEX_ENABLE 0
70 #include <string.h> /* memcpy, etc. */
71 #if TARGET_API_MAC_OSX
72 #include <sys/time.h> /* for timespec */
73 #elif TARGET_API_MAC_CARBON
74 #include <Timer.h> /* Microseconds */
79 #error Unknown TARGET_API
80 #endif /* TARGET_API */
82 #define MUTEX_ENABLE 1
83 #endif /* macintosh */
86 static HANDLE Statmutex
= NULL
;
87 static DWORD mutexCreatorId
= 0;
91 #pragma mark * * * Static Utility functions * * *
93 /* All error checking should be done in the function that calls these */
96 * out := SHA1(IV | out)
99 prng_do_SHA1(GEN_CTX
*ctx
)
104 SHA1Update(&sha
,ctx
->IV
,20);
105 SHA1Update(&sha
,ctx
->out
,20);
106 SHA1Final(ctx
->out
,&sha
);
114 * Called from init, prngForceReseed(), and prngOutput()
115 * as anti-backtracking mechanism.
118 prng_make_new_state(GEN_CTX
*ctx
,BYTE
*newState
)
122 memcpy(ctx
->IV
,newState
,20);
124 SHA1Update(&sha
,ctx
->IV
,20);
125 SHA1Final(ctx
->out
,&sha
);
133 /* Initialize the secret state with a slow poll */
134 /* Currently only called from prngInitialize */
136 #define SPLEN 65536 /* 64K */
139 prng_slow_init(PRNG
*p
)
140 /* This fails silently and must be fixed. */
142 SHA1_CTX
* ctx
= NULL
;
143 MMPTR mmctx
= MM_NULL
;
145 MMPTR mmbigbuf
= MM_NULL
;
147 MMPTR mmbuf
= MM_NULL
;
150 mmbigbuf
= mmMalloc(SPLEN
);
151 if(mmbigbuf
== MM_NULL
) {goto cleanup_slow_init
;}
152 bigbuf
= (BYTE
*)mmGetPtr(mmbigbuf
);
154 mmbuf
= mmMalloc(20);
155 if(mmbuf
== MM_NULL
) {goto cleanup_slow_init
;}
156 buf
= (BYTE
*)mmGetPtr(mmbuf
);
158 mmctx
= mmMalloc(sizeof(SHA1_CTX
));
159 if(mmctx
== MM_NULL
) {goto cleanup_slow_init
;}
160 ctx
= (SHA1_CTX
*)mmGetPtr(mmctx
);
163 /* Initialize the secret state. */
164 /* Init entropy pool */
166 /* Init output generator */
167 polllength
= prng_slow_poll(bigbuf
,SPLEN
);
169 SHA1Update(ctx
,bigbuf
,polllength
);
171 prng_make_new_state(&p
->outstate
, buf
);
181 #endif /* SLOW_POLL_ENABLE */
183 /* In-place modifed bubble sort */
185 bubbleSort(UINT
*data
,UINT len
)
187 UINT i
,last
,newlast
,temp
;
195 if(data
[i
+1] > data
[i
])
208 #pragma mark * * * Public functions * * *
210 /* Set up the PRNG */
212 prngInitialize(PrngRef
*prng
)
215 comp_error_status resp
;
216 prng_error_status retval
= PRNG_ERR_LOW_MEMORY
;
223 /* Create the mutex */
224 /* NOTE: on return the mutex should bve held, since our caller (prngInitialize)
227 if(mutexCreatorId
!=0) {return PRNG_ERR_REINIT
;}
228 Statmutex
= CreateMutex(NULL
,TRUE
,NULL
);
229 if(Statmutex
== NULL
) {mutexCreatorId
= 0; return PRNG_ERR_MUTEX
;}
230 DuplicateHandle(GetCurrentProcess(),Statmutex
,GetCurrentProcess(),&mutex
,SYNCHRONIZE
,FALSE
,0);
231 mutexCreatorId
= GetCurrentProcessId();
232 #endif /* MUTEX_ENABLE */
235 mmp
= mmMalloc(sizeof(PRNG
));
242 p
= (PRNG
*)mmGetPtr(mmp
);
243 memset(p
, 0, sizeof(PRNG
));
246 /* Initialize Variables */
247 for(i
=0;i
<TOTAL_SOURCES
;i
++)
250 p
->poolEstBits
[i
] = 0;
254 /* Setup security on the registry so that remote users cannot predict the slow pool */
255 prng_set_NT_security();
258 /* Initialize the secret state. */
259 /* FIXME - might want to make this an option here and have the caller
260 * do it after we return....? */
263 prng_slow_init(p
); /* Does a slow poll and then calls prng_make_state(...) */
266 prng_do_SHA1(&p
->outstate
);
267 prng_make_new_state(&p
->outstate
, p
->outstate
.out
);
268 #endif /* SLOW_POLL_ENABLE */
270 /* Initialize compression routines */
271 for(i
=0;i
<COMP_SOURCES
;i
++)
273 resp
= comp_init((p
->comp_state
)+i
);
274 if(resp
!=COMP_SUCCESS
) {retval
= PRNG_ERR_COMPRESSION
; goto cleanup_init
;}
277 p
->ready
= PRNG_READY
;
283 /* Program failed on one of the mmmallocs */
288 CloseHandle(Statmutex
);
293 return retval
; /* default PRNG_ERR_LOW_MEMORY */
298 prngOutput(PRNG
*p
, BYTE
*outbuf
,UINT outbuflen
)
301 GEN_CTX
*ctx
= &p
->outstate
;
306 chASSERT(BACKTRACKLIMIT
> 0);
308 for(i
=0;i
<outbuflen
;i
++,ctx
->index
++,ctx
->numout
++)
310 /* Check backtracklimit */
311 if(ctx
->numout
> BACKTRACKLIMIT
)
314 prng_make_new_state(ctx
, ctx
->out
);
316 /* Check position in IV */
322 outbuf
[i
] = (ctx
->out
)[ctx
->index
];
329 /* Cause the PRNG to reseed now regardless of entropy pool */
330 /* Should this be public? */
332 prngForceReseed(PRNG
*p
, LONGLONG ticks
)
336 FILETIME a
,b
,c
,usertime
;
340 #if defined(macintosh) || defined(__APPLE__)
341 #if (defined(TARGET_API_MAC_OSX) || defined(KERNEL_BUILD))
344 #else TARGET_API_MAC_CARBON
345 UnsignedWide uwide
; /* struct needed for Microseconds() */
355 /* Set up start and end times */
356 #if defined(macintosh) || defined(__APPLE__)
357 #if (defined(TARGET_API_MAC_OSX) || defined(KERNEL_BUILD))
358 /* note we can't loop for more than a million microseconds */
362 gettimeofday(&tv
, NULL
);
364 endTime
= tv
.tv_usec
+ ticks
;
365 if(endTime
> 1000000) {
366 /* handle rollover now */
369 #else /* TARGET_API_MAC_OSX */
370 Microseconds(&uwide
);
371 start
= UnsignedWideToUInt64(uwide
);
372 #endif /* TARGET_API_xxx */
373 #endif /* macintosh */
376 /* Do a couple of iterations between time checks */
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);
385 prngOutput(p
, buf
,64);
386 SHA1Update(&p
->pool
,buf
,64);
388 #if defined(macintosh) || defined(__APPLE__)
389 #if defined(TARGET_API_MAC_OSX) || defined(KERNEL_BUILD)
390 #ifdef TARGET_API_MAC_OSX
391 gettimeofday(&tv
, NULL
);
395 } while(tv
.tv_usec
< endTime
);
397 Microseconds(&uwide
);
398 now
= UnsignedWideToUInt64(uwide
);
399 } while ( (now
-start
) < ticks
) ;
402 } while ( (now
-start
) < ticks
) ;
404 SHA1Final(dig
,&p
->pool
);
405 SHA1Update(&p
->pool
,dig
,20);
406 SHA1Final(dig
,&p
->pool
);
408 /* Reset secret state */
410 prng_make_new_state(&p
->outstate
,dig
);
412 /* Clear counter variables */
413 for(i
=0;i
<TOTAL_SOURCES
;i
++)
416 p
->poolEstBits
[i
] = 0;
420 trashMemory(dig
,20*sizeof(char));
421 trashMemory(buf
,64*sizeof(char));
427 /* Input a state into the PRNG */
429 prngProcessSeedBuffer(PRNG
*p
, BYTE
*buf
,LONGLONG ticks
)
435 /* Put the data into the entropy, add some data from the unknown state, reseed */
436 SHA1Update(&p
->pool
,buf
,20); /* Put it into the entropy pool */
437 prng_do_SHA1(&p
->outstate
); /* Output 20 more bytes and */
438 SHA1Update(&p
->pool
,p
->outstate
.out
,20);/* add it to the pool as well. */
439 prngForceReseed(p
, ticks
); /* Do a reseed */
440 return prngOutput(p
, buf
,20); /* Return the first 20 bytes of output in buf */
444 /* Take some "random" data and make more "random-looking" data from it */
445 /* note: this routine has no context, no mutex wrapper */
447 prngStretch(BYTE
*inbuf
,UINT inbuflen
,BYTE
*outbuf
,UINT outbuflen
) {
455 if(inbuflen
>= outbuflen
)
457 memcpy(outbuf
,inbuf
,outbuflen
);
460 else /* Extend using SHA1 hash of inbuf */
463 SHA1Update(&ctx
,inbuf
,inbuflen
);
465 for(prev
=0,left
=outbuflen
;left
>0;prev
+=20,left
-=20)
467 SHA1Update(&ctx
,dig
,20);
469 memcpy(outbuf
+prev
,dig
,(left
>20)?20:left
);
471 trashMemory(dig
,20*sizeof(BYTE
));
476 return PRNG_ERR_PROGRAM_FLOW
;
480 /* Add entropy to the PRNG from a source */
482 prngInput(PRNG
*p
, BYTE
*inbuf
,UINT inbuflen
,UINT poolnum
,UINT estbits
)
484 #ifndef YARROW_KERNEL
485 comp_error_status resp
;
491 if(poolnum
>= TOTAL_SOURCES
) {return PRNG_ERR_OUT_OF_BOUNDS
;}
493 /* Add to entropy pool */
494 SHA1Update(&p
->pool
,inbuf
,inbuflen
);
496 #ifndef YARROW_KERNEL
497 /* skip this step for the kernel */
499 /* Update pool size, pool user estimate and pool compression context */
500 p
->poolSize
[poolnum
] += inbuflen
;
501 p
->poolEstBits
[poolnum
] += estbits
;
502 if(poolnum
<COMP_SOURCES
)
504 resp
= comp_add_data((p
->comp_state
)+poolnum
,inbuf
,inbuflen
);
505 if(resp
!=COMP_SUCCESS
) {return PRNG_ERR_COMPRESSION
;}
507 #endif /* YARROW_KERNEL */
514 /* If we have enough entropy, allow a reseed of the system */
516 prngAllowReseed(PRNG
*p
, LONGLONG ticks
)
518 UINT temp
[TOTAL_SOURCES
];
524 comp_error_status resp
;
529 for(i
=0;i
<ENTROPY_SOURCES
;i
++)
531 /* Make sure that compression-based entropy estimates are current */
532 #ifndef KERNEL_BUILD // floating point in a kernel is BAD!
533 resp
= comp_get_ratio((p
->comp_state
)+i
,&ratio
);
534 if(resp
!=COMP_SUCCESS
) {return PRNG_ERR_COMPRESSION
;}
535 /* Use 4 instead of 8 to half compression estimate */
536 temp
[i
] = (int)(ratio
*p
->poolSize
[i
]*4);
538 temp
[i
] = p
->poolSize
[i
] * 4;
542 /* Use minumum of user and compression estimate for compressed sources */
543 for(i
=ENTROPY_SOURCES
;i
<COMP_SOURCES
;i
++)
546 /* Make sure that compression-based entropy estimates are current */
547 resp
= comp_get_ratio((p
->comp_state
)+i
,&ratio
);
548 if(resp
!=COMP_SUCCESS
) {return PRNG_ERR_COMPRESSION
;}
549 /* Use 4 instead of 8 to half compression estimate */
550 temp
[i
] = _MIN((int)(ratio
*p
->poolSize
[i
]*4),(int)p
->poolEstBits
[i
]);
552 temp
[i
] = _MIN (p
->poolSize
[i
] * 4, p
->poolEstBits
[i
]);
556 /* Use user estimate for remaining sources */
557 for(i
=COMP_SOURCES
;i
<TOTAL_SOURCES
;i
++) {temp
[i
] = p
->poolEstBits
[i
];}
560 /* pointless if we're not ignoring any sources */
561 bubbleSort(temp
,TOTAL_SOURCES
);
563 for(i
=K
,sum
=0;i
<TOTAL_SOURCES
;sum
+=temp
[i
++]); /* Stupid C trick */
565 return prngForceReseed(p
, ticks
);
567 return PRNG_ERR_NOT_ENOUGH_ENTROPY
;
569 return PRNG_ERR_PROGRAM_FLOW
;
573 /* Call a slow poll and insert the data into the entropy pool */
574 static prng_error_status
575 prngSlowPoll(PRNG
*p
, UINT pollsize
)
579 prng_error_status retval
;
583 buf
= (BYTE
*)malloc(pollsize
);
584 if(buf
==NULL
) {return PRNG_ERR_LOW_MEMORY
;}
585 len
= prng_slow_poll(buf
,pollsize
); /* OS specific call */
586 retval
= prngInput(p
, buf
,len
,SLOWPOLLSOURCE
, len
* 8);
587 trashMemory(buf
,pollsize
);
592 #endif /* SLOW_POLL_ENABLE */
595 /* Delete the PRNG */
602 if(GetCurrentProcessId()!=mutexCreatorId
) {return PRNG_ERR_WRONG_CALLER
;}
604 if(p
==NULL
) {return PRNG_SUCCESS
;} /* Well, there is nothing to destroy... */
606 p
->ready
= PRNG_NOT_READY
;
608 for(i
=0;i
<COMP_SOURCES
;i
++)
610 comp_end((p
->comp_state
)+i
);
614 CloseHandle(Statmutex
);