2 * Copyright (c) 1999, 2000-2001 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_OSREFERENCE_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. The rights granted to you under the
10 * License may not be used to create, or enable the creation or
11 * redistribution of, unlawful or unlicensed copies of an Apple operating
12 * system, or to circumvent, violate, or enable the circumvention or
13 * violation of, any terms of an Apple operating system software license
16 * Please obtain a copy of the License at
17 * http://www.opensource.apple.com/apsl/ and read it before using this
20 * The Original Code and all software distributed under the License are
21 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
22 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
23 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
24 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
25 * Please see the License for the specific language governing rights and
26 * limitations under the License.
28 * @APPLE_LICENSE_OSREFERENCE_HEADER_END@
34 Contains: Core routines for the Counterpane Yarrow PRNG.
36 Written by: Counterpane, Inc.
38 Copyright: (c) 2000 by Apple Computer, Inc., all rights reserved.
40 Change History (most recent first):
42 02/10/99 dpm Created, based on Counterpane source.
48 Core routines for the Counterpane PRNG
50 #include "userdefines.h"
51 #include "assertverify.h"
52 #include "dev/random/YarrowCoreLib/include/yarrowUtils.h"
54 #if defined(macintosh) || defined(__APPLE__)
55 /* FIXME - this file needs to be in a platform-independent place */
58 #endif /* macintosh */
61 #include "entropysources.h"
63 #include "dev/random/YarrowCoreLib/include/yarrow.h"
68 #define _MAX(a,b) (((a)>(b))?(a):(b))
69 #define _MIN(a,b) (((a)<(b))?(a):(b))
71 #if defined(macintosh) || defined(__APPLE__)
73 * No mutexes in this module for Macintosh/OSX. We handle the
74 * required locking elsewhere.
76 #define MUTEX_ENABLE 0
78 #include <string.h> /* memcpy, etc. */
79 #if TARGET_API_MAC_OSX
80 #include <sys/time.h> /* for timespec */
81 #elif TARGET_API_MAC_CARBON
82 #include <Timer.h> /* Microseconds */
87 #error Unknown TARGET_API
88 #endif /* TARGET_API */
90 #define MUTEX_ENABLE 1
91 #endif /* macintosh */
94 static HANDLE Statmutex
= NULL
;
95 static DWORD mutexCreatorId
= 0;
99 #pragma mark * * * Static Utility functions * * *
101 /* All error checking should be done in the function that calls these */
104 * out := SHA1(IV | out)
107 prng_do_SHA1(GEN_CTX
*ctx
)
112 SHA1Update(&sha
,ctx
->IV
,20);
113 SHA1Update(&sha
,ctx
->out
,20);
114 SHA1Final(ctx
->out
,&sha
);
122 * Called from init, prngForceReseed(), and prngOutput()
123 * as anti-backtracking mechanism.
126 prng_make_new_state(GEN_CTX
*ctx
,BYTE
*newState
)
130 memcpy(ctx
->IV
,newState
,20);
132 SHA1Update(&sha
,ctx
->IV
,20);
133 SHA1Final(ctx
->out
,&sha
);
141 /* Initialize the secret state with a slow poll */
142 /* Currently only called from prngInitialize */
144 #define SPLEN 65536 /* 64K */
147 prng_slow_init(PRNG
*p
)
148 /* This fails silently and must be fixed. */
150 SHA1_CTX
* ctx
= NULL
;
151 MMPTR mmctx
= MM_NULL
;
153 MMPTR mmbigbuf
= MM_NULL
;
155 MMPTR mmbuf
= MM_NULL
;
158 mmbigbuf
= mmMalloc(SPLEN
);
159 if(mmbigbuf
== MM_NULL
) {goto cleanup_slow_init
;}
160 bigbuf
= (BYTE
*)mmGetPtr(mmbigbuf
);
162 mmbuf
= mmMalloc(20);
163 if(mmbuf
== MM_NULL
) {goto cleanup_slow_init
;}
164 buf
= (BYTE
*)mmGetPtr(mmbuf
);
166 mmctx
= mmMalloc(sizeof(SHA1_CTX
));
167 if(mmctx
== MM_NULL
) {goto cleanup_slow_init
;}
168 ctx
= (SHA1_CTX
*)mmGetPtr(mmctx
);
171 /* Initialize the secret state. */
172 /* Init entropy pool */
174 /* Init output generator */
175 polllength
= prng_slow_poll(bigbuf
,SPLEN
);
177 SHA1Update(ctx
,bigbuf
,polllength
);
179 prng_make_new_state(&p
->outstate
, buf
);
189 #endif /* SLOW_POLL_ENABLE */
191 /* In-place modifed bubble sort */
193 bubbleSort( UINT
*data
, LONG len
)
204 if(data
[i
+1] > data
[i
])
217 #pragma mark * * * Public functions * * *
219 /* Set up the PRNG */
221 prngInitialize(PrngRef
*prng
)
224 comp_error_status resp
;
225 prng_error_status retval
= PRNG_ERR_LOW_MEMORY
;
232 /* Create the mutex */
233 /* NOTE: on return the mutex should bve held, since our caller (prngInitialize)
236 if(mutexCreatorId
!=0) {return PRNG_ERR_REINIT
;}
237 Statmutex
= CreateMutex(NULL
,TRUE
,NULL
);
238 if(Statmutex
== NULL
) {mutexCreatorId
= 0; return PRNG_ERR_MUTEX
;}
239 DuplicateHandle(GetCurrentProcess(),Statmutex
,GetCurrentProcess(),&mutex
,SYNCHRONIZE
,FALSE
,0);
240 mutexCreatorId
= GetCurrentProcessId();
241 #endif /* MUTEX_ENABLE */
244 mmp
= mmMalloc(sizeof(PRNG
));
251 p
= (PRNG
*)mmGetPtr(mmp
);
252 memset(p
, 0, sizeof(PRNG
));
255 /* Initialize Variables */
256 for(i
=0;i
<TOTAL_SOURCES
;i
++)
259 p
->poolEstBits
[i
] = 0;
263 /* Setup security on the registry so that remote users cannot predict the slow pool */
264 prng_set_NT_security();
267 /* Initialize the secret state. */
268 /* FIXME - might want to make this an option here and have the caller
269 * do it after we return....? */
272 prng_slow_init(p
); /* Does a slow poll and then calls prng_make_state(...) */
275 prng_do_SHA1(&p
->outstate
);
276 prng_make_new_state(&p
->outstate
, p
->outstate
.out
);
277 #endif /* SLOW_POLL_ENABLE */
279 /* Initialize compression routines */
280 for(i
=0;i
<COMP_SOURCES
;i
++)
282 resp
= comp_init((p
->comp_state
)+i
);
283 if(resp
!=COMP_SUCCESS
) {retval
= PRNG_ERR_COMPRESSION
; goto cleanup_init
;}
286 p
->ready
= PRNG_READY
;
292 /* Program failed on one of the mmmallocs */
297 CloseHandle(Statmutex
);
302 return retval
; /* default PRNG_ERR_LOW_MEMORY */
307 prngOutput(PRNG
*p
, BYTE
*outbuf
,UINT outbuflen
)
310 GEN_CTX
*ctx
= &p
->outstate
;
315 chASSERT(BACKTRACKLIMIT
> 0);
317 for(i
=0;i
<outbuflen
;i
++,ctx
->index
++,ctx
->numout
++)
319 /* Check backtracklimit */
320 if(ctx
->numout
> BACKTRACKLIMIT
)
323 prng_make_new_state(ctx
, ctx
->out
);
325 /* Check position in IV */
331 outbuf
[i
] = (ctx
->out
)[ctx
->index
];
338 /* Cause the PRNG to reseed now regardless of entropy pool */
339 /* Should this be public? */
341 prngForceReseed(PRNG
*p
, LONGLONG ticks
)
345 FILETIME a
,b
,c
,usertime
;
349 #if defined(macintosh) || defined(__APPLE__)
350 #if (defined(TARGET_API_MAC_OSX) || defined(KERNEL_BUILD))
352 int64_t endTime
, curTime
;
353 #else /* TARGET_API_MAC_CARBON */
354 UnsignedWide uwide
; /* struct needed for Microseconds() */
364 /* Set up start and end times */
365 #if defined(macintosh) || defined(__APPLE__)
366 #if (defined(TARGET_API_MAC_OSX) || defined(KERNEL_BUILD))
367 /* note we can't loop for more than a million microseconds */
371 gettimeofday(&tv
, NULL
);
373 endTime
= (int64_t)tv
.tv_sec
*1000000LL + (int64_t)tv
.tv_usec
+ ticks
;
374 #else /* TARGET_API_MAC_OSX */
375 Microseconds(&uwide
);
376 start
= UnsignedWideToUInt64(uwide
);
377 #endif /* TARGET_API_xxx */
378 #endif /* macintosh */
381 /* Do a couple of iterations between time checks */
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);
390 prngOutput(p
, buf
,64);
391 SHA1Update(&p
->pool
,buf
,64);
393 #if defined(macintosh) || defined(__APPLE__)
394 #if defined(TARGET_API_MAC_OSX) || defined(KERNEL_BUILD)
395 #ifdef TARGET_API_MAC_OSX
396 gettimeofday(&tv
, NULL
);
399 curTime
= (int64_t)tv
.tv_sec
*1000000LL + (int64_t)tv
.tv_usec
;
401 } while(curTime
< endTime
);
403 Microseconds(&uwide
);
404 now
= UnsignedWideToUInt64(uwide
);
405 } while ( (now
-start
) < ticks
) ;
408 } while ( (now
-start
) < ticks
) ;
410 SHA1Final(dig
,&p
->pool
);
411 SHA1Update(&p
->pool
,dig
,20);
412 SHA1Final(dig
,&p
->pool
);
414 /* Reset secret state */
416 prng_make_new_state(&p
->outstate
,dig
);
418 /* Clear counter variables */
419 for(i
=0;i
<TOTAL_SOURCES
;i
++)
422 p
->poolEstBits
[i
] = 0;
426 trashMemory(dig
,20*sizeof(char));
427 trashMemory(buf
,64*sizeof(char));
433 /* Input a state into the PRNG */
435 prngProcessSeedBuffer(PRNG
*p
, BYTE
*buf
,LONGLONG ticks
)
441 /* Put the data into the entropy, add some data from the unknown state, reseed */
442 SHA1Update(&p
->pool
,buf
,20); /* Put it into the entropy pool */
443 prng_do_SHA1(&p
->outstate
); /* Output 20 more bytes and */
444 SHA1Update(&p
->pool
,p
->outstate
.out
,20);/* add it to the pool as well. */
445 prngForceReseed(p
, ticks
); /* Do a reseed */
446 return prngOutput(p
, buf
,20); /* Return the first 20 bytes of output in buf */
450 /* Take some "random" data and make more "random-looking" data from it */
451 /* note: this routine has no context, no mutex wrapper */
453 prngStretch(BYTE
*inbuf
,UINT inbuflen
,BYTE
*outbuf
,UINT outbuflen
) {
461 if(inbuflen
>= outbuflen
)
463 memcpy(outbuf
,inbuf
,outbuflen
);
466 else /* Extend using SHA1 hash of inbuf */
469 SHA1Update(&ctx
,inbuf
,inbuflen
);
471 for(prev
=0,left
=outbuflen
;left
>0;prev
+=20,left
-=20)
473 SHA1Update(&ctx
,dig
,20);
475 memcpy(outbuf
+prev
,dig
,(left
>20)?20:left
);
477 trashMemory(dig
,20*sizeof(BYTE
));
482 return PRNG_ERR_PROGRAM_FLOW
;
486 /* Add entropy to the PRNG from a source */
488 prngInput(PRNG
*p
, BYTE
*inbuf
,UINT inbuflen
,UINT poolnum
, __unused UINT estbits
)
490 #ifndef YARROW_KERNEL
491 comp_error_status resp
;
497 if(poolnum
>= TOTAL_SOURCES
) {return PRNG_ERR_OUT_OF_BOUNDS
;}
499 /* Add to entropy pool */
500 SHA1Update(&p
->pool
,inbuf
,inbuflen
);
502 #ifndef YARROW_KERNEL
503 /* skip this step for the kernel */
505 /* Update pool size, pool user estimate and pool compression context */
506 p
->poolSize
[poolnum
] += inbuflen
;
507 p
->poolEstBits
[poolnum
] += estbits
;
508 if(poolnum
<COMP_SOURCES
)
510 resp
= comp_add_data((p
->comp_state
)+poolnum
,inbuf
,inbuflen
);
511 if(resp
!=COMP_SUCCESS
) {return PRNG_ERR_COMPRESSION
;}
513 #endif /* YARROW_KERNEL */
520 /* If we have enough entropy, allow a reseed of the system */
522 prngAllowReseed(PRNG
*p
, LONGLONG ticks
)
524 UINT temp
[TOTAL_SOURCES
];
532 comp_error_status resp
;
537 for(i
=0;i
<ENTROPY_SOURCES
;i
++)
539 /* Make sure that compression-based entropy estimates are current */
540 #ifndef KERNEL_BUILD // floating point in a kernel is BAD!
541 resp
= comp_get_ratio((p
->comp_state
)+i
,&ratio
);
542 if(resp
!=COMP_SUCCESS
) {return PRNG_ERR_COMPRESSION
;}
543 /* Use 4 instead of 8 to half compression estimate */
544 temp
[i
] = (int)(ratio
*p
->poolSize
[i
]*4);
546 temp
[i
] = p
->poolSize
[i
] * 4;
550 /* Use minumum of user and compression estimate for compressed sources */
551 for(i
=ENTROPY_SOURCES
;i
<COMP_SOURCES
;i
++)
554 /* Make sure that compression-based entropy estimates are current */
555 resp
= comp_get_ratio((p
->comp_state
)+i
,&ratio
);
556 if(resp
!=COMP_SUCCESS
) {return PRNG_ERR_COMPRESSION
;}
557 /* Use 4 instead of 8 to half compression estimate */
558 temp
[i
] = _MIN((int)(ratio
*p
->poolSize
[i
]*4),(int)p
->poolEstBits
[i
]);
560 temp
[i
] = _MIN (p
->poolSize
[i
] * 4, p
->poolEstBits
[i
]);
564 /* Use user estimate for remaining sources */
565 for(i
=COMP_SOURCES
;i
<TOTAL_SOURCES
;i
++) {temp
[i
] = p
->poolEstBits
[i
];}
568 /* pointless if we're not ignoring any sources */
569 bubbleSort(temp
,TOTAL_SOURCES
);
571 for(i
=K
,sum
=0;i
<TOTAL_SOURCES
;sum
+=temp
[i
++]); /* Stupid C trick */
573 return prngForceReseed(p
, ticks
);
575 return PRNG_ERR_NOT_ENOUGH_ENTROPY
;
577 return PRNG_ERR_PROGRAM_FLOW
;
581 /* Call a slow poll and insert the data into the entropy pool */
582 static prng_error_status
583 prngSlowPoll(PRNG
*p
, UINT pollsize
)
587 prng_error_status retval
;
591 buf
= (BYTE
*)malloc(pollsize
);
592 if(buf
==NULL
) {return PRNG_ERR_LOW_MEMORY
;}
593 len
= prng_slow_poll(buf
,pollsize
); /* OS specific call */
594 retval
= prngInput(p
, buf
,len
,SLOWPOLLSOURCE
, len
* 8);
595 trashMemory(buf
,pollsize
);
600 #endif /* SLOW_POLL_ENABLE */
603 /* Delete the PRNG */
610 if(GetCurrentProcessId()!=mutexCreatorId
) {return PRNG_ERR_WRONG_CALLER
;}
612 if(p
==NULL
) {return PRNG_SUCCESS
;} /* Well, there is nothing to destroy... */
614 p
->ready
= PRNG_NOT_READY
;
616 for(i
=0;i
<COMP_SOURCES
;i
++)
618 comp_end((p
->comp_state
)+i
);
622 CloseHandle(Statmutex
);