1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
|
/*
* Copyright (c) mjh-EDV Beratung, 1996-1999
* mjh-EDV Beratung - 63263 Neu-Isenburg - Rosenstrasse 12
* Tel +49 6102 328279 - Fax +49 6102 328278
* Email info@mjh.teddy-net.com
*
* Author: Jordan Hrycaj <jordan@mjh.teddy-net.com>
*
* $Id: rnd-pool.c,v 1.14.2.2 2001/06/15 21:45:11 renaud Exp $
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "common-stuff.h"
#include <fcntl.h>
#ifdef USE_PTHREADS
#ifdef HAVE_PTHREAD_H
#include <pthread.h>
#endif
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#else
#define assert(x)
#endif
#ifndef HAVE_RAND
#define rand() random ()
#endif
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#include "cipher/cipher.h"
#include "messages.h"
#include "rand/rnd-pool.h"
#define DUMP_MUTEX
#define DEBUG_DENSITY 1 /* comment on unexpected results */
/* ------------------------------------------------------------------------- *
* private defs and data and structures *
* ------------------------------------------------------------------------- */
#define HASH_TYPE "ripemd160"
#define COMPRESSION_UNIT 3 /* an integer: 3 units are compressed to 1 */
#ifdef HAVE_DEV_RANDOM
# ifndef DEV_RANDOM
# define DEV_RANDOM "/dev/urandom"
# endif /* DEV_RANDOM */
static const char *dev_random = DEV_RANDOM;
/* for each user defined byte add some data from the /dev/random */
# define add_dev_randomness_len(b) (b) /* the same weight, currently */
static int devrnd = -2 ; /* try to open once, only */
#endif /* HAVE_DEV_RANDOM */
# define WARN_LOG2(f,x) (fputs ("WARNING: ",stderr),\
fprintf(stderr,f,x),\
fflush (stderr))
# define WARN_LOG3(f,x,y) (fputs ("WARNING: ",stderr),\
fprintf(stderr,f,x,y),\
fflush (stderr))
/* #undef RND_POOL_SIZE */
/* #define RND_POOL_SIZE 500 */
/* ------------------------------------------------------------------------- *
* private variables *
* ------------------------------------------------------------------------- */
/* the fifo with random data */
static char pool [RND_POOL_SIZE] ;
static int get_inx = -1, put_inx = 0 ;
/* number of bytes in the pool not compressed, yet */
static int uncompressed = 0;
/* The density gives a means to check whats in the pool. It is
calculated total
#in-data - #out-data - #uncompressed
ro = -------------------------------------
sizeof (pool)
Remark: If greater 1, more data are put in the pool than ita formal
size. With the compressing, this tells how many input bits
are at least used in order to create one output bit.
The #uncompressed variable reflects the fact, that the pool
is filled up constantly and compressed only, when enough data
are present to compress the pool altogether.
One should note, that the act of compressing data only
changes the #uncompressed parameter. If this parameter is
small, the density does not significantly change although the
bits available are less them before compressing.
Due to the compressor block size (usually 3*20 == 60 bytes,
COMPRESSION_UNIT times the value of the hash buffer), the
number of bits making up an output bit is at most O(ro) with
a big O constant larget than 1 dependent on the compressor
algorithm only: sizeof(pool)/compressor-block-size >> 1.
In any case, ro is a lower bound for the number of bits at
least used in order to create one output bit.
Adding some data #delta-in, leaving #uncompressed' data uncompressed
and probably compresssing results in the incremental formula
#in-data + #delta-in - #out-data - #uncompressed'
ro' = ------------------------------------------------- =
sizeof (pool)
#delta-in - #delta-uncompressed
= ro + -------------------------------
sizeof (pool)
(where #delta-uncompressed = #uncompressed' - uncompressed)
Remark: In weird cases, adding data may decrease the density, the
lower bound for the number of input bits that make up an
output bit.
Assume there are no uncompressed data in the pool and you
compress it. In this case, #delta-in == 0. Due to the
compressing algorithm, there might show up some data left
uncompressed in the current round, giving ro < ro.
One might argue, that the data left uncompressed in the
current round might have been compressed by an earlier
round. But as the compressor algorithm is thought of evenly
mix and spread the compressed data, the uncompressed data
left over have another density. So we just let the lower
bound decrease, the maximum decrement being significantly
smaller than 1: compressor-block-size/sizeof(pool) << 1.
Removing some data #delta-out gives
#in-data - #out-data - #uncompressed - #delta-out
ro" = ------------------------------------------------- =
sizeof (pool)
#delta-out
= ro - -------------
sizeof (pool)
Remark: Removing data always decreases the lower bound only,
although the number of input bits that make up an output bit
may remain the same.
*/
static float density = 0, maximum_density = 1e30;
/* the same as above but public for easy checking */
unsigned i100density, imax_density = (unsigned)-1 ;
/* ------------------------------------------------------------------------- *
* private functions *
* ------------------------------------------------------------------------- */
#define SYSNAME "rnd-pool"
#include "peks-sema.h"
/*
* organization of the fifo:
* -------------------------
*
*
* 1. standard case
* ----------------
*
* output
* /\
* ||
* | | <- 0, bottom
* | |
* | XX | <- get_inx, first busy entry
* | XX |
* | XX |
* | :: |
* | |
* | XX |
* | | <- put_inx, first free entry
* | |
* /\ <- DIM, 1 beyond largest index
* ||
* input
*
*
* 2. wrap around
* --------------
*
* | XX | <- 0, bottom
* | XX |
* | | <- put_inx, first free entry
* | |
* | |
* | XX | <- get_inx, first busy entry
* | XX |
* | :: |
* | |
* | XX |
* | XX |
* <- DIM, 1 beyond largest address
*
*
* 3. fifo full/empty
* ------------------
*
* full: put_inx == get_inx >= 0
* not full: put_inx != get_inx
* empty: put_inx > get_inx == -1
*/
#if 0
static unsigned
pool_size (void)
{
int n ;
if ((n = (put_inx - get_inx)) <= 0)
return sizeof (pool) + n ;
return get_inx < 0 ? 0 : n ;
}
#else
#define pool_size() (put_inx <= get_inx \
? sizeof (pool) + put_inx - get_inx \
: (get_inx >= 0 ? put_inx - get_inx : 0) )
#endif
static unsigned /* returns number of bytes stored */
put_data
(const char *p,
unsigned n)
{
unsigned avail, stored = 0 ;
if (n == 0)
/* nothing to do */
return 0;
/* 1st case, normal mode, fifo may be empty */
if (get_inx < put_inx) {
/* store the maximum value, possible */
if ((stored = sizeof (pool) - put_inx) > n)
stored = n ;
memcpy (pool + put_inx, p, stored) ;
/* update indices, wrap around if necessary */
if ((put_inx += stored) == sizeof (pool))
put_inx = 0 ; /* wrap around */
if (get_inx < 0)
get_inx = 0 ; /* pool was empty */
/* done, everything stored ? */
if (n == stored)
return stored ;
/* otherwise proceed with the 2nd case, here put_inx == 0 */
n -= stored ;
p += stored ;
}
/* 2nd case, calculate the space, available */
if ((avail = get_inx - put_inx) == 0)
/* fifo full, no more data stored */
return stored ;
/* store the maximum value, possible */
if (avail > n)
avail = n ;
memcpy (pool + put_inx, p, avail) ;
/* update index */
put_inx += avail ;
return stored + avail ;
}
static unsigned /* returns the number of data, retrieved */
get_data
(char *p,
unsigned n)
{
unsigned avail, retrieved = 0 ;
if (n == 0)
/* nothing to do */
return 0;
/* do the 2nd case, fifo may be full */
if (get_inx >= put_inx) {
/* get as much as possible */
if ((retrieved = sizeof (pool) - get_inx) > n)
retrieved = n ;
memcpy (p, pool + get_inx, retrieved) ;
/* update index, fifo might be empty, now */
if ((get_inx += retrieved) == sizeof (pool))
get_inx = put_inx ? 0 : -1 ;
/* done, everything loaded ? */
if (n == retrieved)
return retrieved;
/* otherwise proceed with the 1st case, here: get_inx <= 0 */
n -= retrieved ;
p += retrieved ;
}
/* 1st case, normal mode, fifo may be empty */
if (get_inx < 0)
return retrieved ;
/* get the maximum value, possible */
if ((avail = (put_inx - get_inx)) > n)
avail = n;
memcpy (p, pool + get_inx, avail) ;
/* update index, fifo may become empty */
if ((get_inx += avail) == put_inx) {
put_inx = 0;
get_inx = -1;
}
return retrieved + avail ;
}
static unsigned /* returns data not compressed, yet */
compress_data (void)
{
static frame_desc *md ;
char *s ;
int chunk, len, n ;
if (md == 0) {
md = create_frame (find_frame_class (HASH_TYPE), 0);
assert (md != 0);
}
/* buffer size: compression unit + overlapping space */
chunk = COMPRESSION_UNIT * md->mdlen ;
/* it makes no sense to compress less data */
if ((len = pool_size ()) < chunk)
return chunk - len ;
/* allocate block compression buffer */
s = ALLOCA (chunk + md->mdlen);
/* start: fill the overlapping space */
len -= get_data (s + chunk, md->mdlen) ;
/* loop over the number of remaining data in the pool */
while (len >= chunk) {
/* shift left the overlapping space */
memcpy (s, s + chunk, md->mdlen);
/* append next data */
n = get_data (s + md->mdlen, chunk);
/* hash the compression unit + overlapping space */
XCRCFIRST (md, s, n + md->mdlen);
/* replace the compressed unit */
put_data (XCRCRESULT0 (md), md->mdlen);
/* update counter */
len -= n;
}
DEALLOCA (s);
return len ;
}
#ifdef HAVE_DEV_RANDOM
static void
open_random
(void)
{
if (dev_random == 0) devrnd = -1 ; /* try to open once, only */
if (devrnd >= -1) return ;
__enter_lock_semaphore () ;
if (devrnd < 0 && (devrnd = open (dev_random, O_RDONLY)) < 0) {
WARN_LOG3 ("Cannot open random device \"%s\": %s.\n",
dev_random, strerror (errno));
}
__release_lock_semaphore () ;
}
#endif /* HAVE_DEV_RANDOM */
/* ------------------------------------------------------------------------- *
* public functions *
* ------------------------------------------------------------------------- */
/* create some weak random bytes */
void
make_random_bytes
(void *p,
int n)
{
char *pc = p;
# ifdef HAVE_DEV_RANDOM
if (devrnd < -1) /* try to open once, only */
open_random () ;
if (devrnd >= 0) {
/* read from random device, if possible */
int m;
fd_set rd;
struct timeval tv = {0,10000};
FD_ZERO(&rd);
FD_SET(devrnd, &rd);
if(select(devrnd + 1, &rd, NULL, NULL, &tv) <= 0)
goto lastresort;
m = read (devrnd, p, n) ;
if (m >= n) return ;
if (m >= 0 ) {
WARN_LOG2 ("Random device \"%s\" runs out of entropy.\n", dev_random);
n -= m ;
p += m ;
} else {
WARN_LOG3 ("Cannot read from random device \"%s\": %s.\n",
dev_random, strerror (errno));
}
}
lastresort:
# endif /* HAVE_DEV_RANDOM */
/* last resort -- do your best */
while (n --) {
/* calculate an integer smaller than 256.0 - 1/(RAND_MAX-1.0) */
* (pc) ++ = (unsigned char)(256.0 * rand () / (RAND_MAX+1.0)) ;
}
}
unsigned
get_random_pool_data
(char *buf,
unsigned len)
{
int retrieved, size, available ;
__enter_lock_semaphore () ;
size = pool_size () ;
available = size - uncompressed ;
# ifdef DEBUG_DENSITY
/* which is the case that cannot happen */
if (available < 0) {
WARN_LOG3 ("get_random_pool_data: pool_size=%d < uncompressed=%d "
"-- please report.\n",
size, uncompressed);
WARN_LOG3 ("get_random_pool_data(cont): put_inx=%d, get_inx=%d "
"-- please report.\n",
put_inx, get_inx);
uncompressed = size ;
available = 0 ;
}
# endif
/* dont let out any data compressed at least once */
if (available == 0) {
# ifdef DEBUG_DENSITY
if (i100density > 50) {
WARN_LOG3 ("get_random_pool_data: i100density=%d(%.2f)"
" rounding error unexpectedly large"
"-- please report.\n",
i100density, density);
}
# endif
/* the density might be slightly positive due to rounding errors */
density = 0 ;
i100density = 0 ;
__release_lock_semaphore () ;
return 0;
}
/* deliver data from the pool */
if (len > available)
len = available ;
retrieved = get_data (buf, len) ;
if ((size = pool_size ()) <= uncompressed) {
density = 0 ;
i100density = 0 ;
} else {
density -= (((float)retrieved) / ((float)sizeof (pool)));
i100density = (100.0 * density) ;
}
__release_lock_semaphore () ;
return retrieved ;
}
/* ------------------------------------------------------------ */
#if defined (USE_PTHREADS) || defined (HAVE_DEV_RANDOM)
static unsigned put_random_pool_data_nosync
(const char *buf, unsigned len) ;
unsigned
put_random_pool_data
(const char *buf,
unsigned len)
{
int n ;
__enter_lock_semaphore () ;
n = put_random_pool_data_nosync (buf, len);
# ifdef HAVE_DEV_RANDOM
if (devrnd >= 0) {
/* add some more randomness */
int m = add_dev_randomness_len (len) ;
void *p = alloca (m);
make_random_bytes (p, m) ;
put_random_pool_data_nosync (p, n);
}
# endif /* HAVE_DEV_RANDOM */
__release_lock_semaphore () ;
return n;
}
static /* function def follows ... */
#else
#define put_random_pool_data_nosync put_random_pool_data
#endif
/* ------------------------------------------------------------ */
unsigned
put_random_pool_data_nosync
(const char *buf,
unsigned len)
{
int n, processed, left, old_uncompr;
float delta ;
old_uncompr = uncompressed ;
left = len ;
processed = 0 ;
n = 0 ;
while (left && (n = put_data (buf + processed, left)) < left) {
processed += n ;
left -= n ;
uncompressed = compress_data () ;
}
if (left) /* (left > 0) => (n == left) */
uncompressed += n;
/* calculate the effect on the density */
if ((delta = (int)len - uncompressed + old_uncompr) == 0)
return len ;
delta /= sizeof (pool) ;
/* the density is a lower bound, only */
if ((density += delta) < 0) {
# ifdef DEBUG_DENSITY
WARN_LOG3 ("put_random_pool_data: delta=%.2f ==> density=%.2f"
" unexpected pool density underflow -- please report.\n",
delta, density);
# endif
density = 0 ;
i100density = 0 ;
return len ;
}
i100density = (100.0 * density) ;
return len ;
}
void
point_of_random_time
(const char *buf,
unsigned len)
{
__enter_lock_semaphore () ;
if (i100density >= imax_density) {
# ifdef DEBUG_DENSITY_LEVEL
WARN_LOG3 ("Density %.3f better than max(%.3f) -- not collecting data.\n",
density, maximum_density);
# endif
return;
}
# ifdef DEBUG_DENSITY_LEVEL
WARN_LOG3 ("Density %.3f, max = %.3f -- collecting random data.\n",
density, maximum_density);
# endif
{
# ifdef HAVE_GETTIMEOFDAY2
/* current time in millisecs, or centisecs etc. */
struct timeval tv ; gettimeofday2 (&tv, 0);
put_random_pool_data_nosync ((char*)&tv, sizeof (tv));
# ifdef HAVE_DEV_RANDOM
make_random_bytes (&tv, sizeof (tv)) ;
put_random_pool_data_nosync ((void*)&tv, sizeof (tv));
# endif /* HAVE_DEV_RANDOM */
# else
time_t ti = time (0);
put_random_pool_data_nosync ((char*)&ti, sizeof (ti));
# ifdef HAVE_DEV_RANDOM
make_random_bytes (&ti, sizeof (ti)) ;
put_random_pool_data_nosync (&ti, sizeof (ti));
# endif /* HAVE_DEV_RANDOM */
# endif
}
# ifdef HAVE_DEV_RANDOM
if (devrnd >= 0) {
char p [30];
make_random_bytes (p, sizeof (p)) ;
put_random_pool_data_nosync (p, sizeof (p));
} else
# endif /* HAVE_DEV_RANDOM */
{
/* output from the random generator */
int r = rand () ;
put_random_pool_data_nosync ((char*)&r, sizeof (r));
}
/* check, whether the user has some more */
if (buf == 0 || len == 0) {
__release_lock_semaphore () ;
return ;
}
put_random_pool_data_nosync (buf, len);
# ifdef HAVE_DEV_RANDOM
/* add some more random bits */
if (devrnd >= 0) {
int n = add_dev_randomness_len (len) ;
void *p = alloca (n);
make_random_bytes (p, n) ;
put_random_pool_data_nosync (p, n);
}
# endif /* HAVE_DEV_RANDOM */
{
# ifdef HAVE_GETTIMEOFDAY2
/* again, current time in millisecs, or centisecs etc. */
struct timeval tv ; gettimeofday2 (&tv, 0);
put_random_pool_data_nosync ((char*)&tv, sizeof (tv));
# else
time_t ti = time (0);
put_random_pool_data_nosync ((char*)&ti, sizeof (ti));
# endif
}
__release_lock_semaphore () ;
}
const char *
use_random_device
(const char *dev)
{
# ifdef HAVE_DEV_RANDOM
const char *s = dev_random ;
if (devrnd >= 0) {
close (devrnd) ;
devrnd = -2;
}
dev_random = dev ;
# else
return 0;
# endif
}
unsigned
random_pool_density_percentage
(void)
{
unsigned n;
__enter_lock_semaphore () ;
n = i100density ;
__release_lock_semaphore () ;
return n;
}
unsigned
max_random_pool_density_percentage
(unsigned d)
{
unsigned n ;
__enter_lock_semaphore () ;
n = imax_density ;
imax_density = d ;
maximum_density = (float)d / 100.0 ;
__release_lock_semaphore () ;
return n;
}
#ifdef USE_PTHREADS
void rnd_pool_sema_create (void *attr) { __sema_create (attr); }
void rnd_pool_sema_destroy (void) { __sema_destroy (); }
#endif
|