Add the --threshold option

Add an option to feed the kernel entropy pool with random data
only when the available entropy falls below a given threshold.
pull/1/head
Damien Goutte-Gattat 8 years ago
parent 0409e47a91
commit ee55272499
  1. 39
      src/scdrand.c

@ -64,6 +64,12 @@ specified, the default is %d bytes.\n\n", DEFAULT_RANDOM_BYTES);
(default: %d seconds).\n\
\n", DEFAULT_LOOP_ITERATIONS, DEFAULT_LOOP_INTERVAL);
puts("\
-t, --threshold N Do nothing if there is already N bits\n\
of entropy available in the kernel pool.\n\
Set to 0 (default) to always add entropy.\n\
");
printf("Report bugs to <%s>.\n", PACKAGE_BUGREPORT);
exit(status);
@ -246,6 +252,22 @@ connect_to_scdaemon(void)
return ctx;
}
static int
get_available_entropy(void)
{
int random_fd, entropy;
if ( (random_fd = open("/dev/random", O_RDONLY)) == -1 )
err(EXIT_FAILURE, "Cannot open /dev/random");
if ( ioctl(random_fd, RNDGETENTCNT, &entropy) == -1 )
err(EXIT_FAILURE, "Cannot get available entropy");
close(random_fd);
return entropy;
}
/*
* Fork a new process solely charged with the task of adding entropy
* to the kernel pool (the only task that requires root privileges).
@ -330,7 +352,7 @@ int
main(int argc, char **argv)
{
int c, fd, n, loop;
unsigned nbytes, interval;
unsigned nbytes, interval, threshold;
assuan_context_t ctx;
unsigned char random_buffer[MAX_RANDOM_BYTES];
@ -340,6 +362,7 @@ main(int argc, char **argv)
{ "loop", 0, NULL, 'l' },
{ "max-loop", 1, NULL, 'L' },
{ "interval", 1, NULL, 'i' },
{ "threshold", 1, NULL, 't' },
{ NULL, 0, NULL, 0 }
};
@ -347,8 +370,9 @@ main(int argc, char **argv)
nbytes = DEFAULT_RANDOM_BYTES;
loop = DEFAULT_LOOP_ITERATIONS;
interval = DEFAULT_LOOP_INTERVAL;
threshold = 0;
while ( (c = getopt_long(argc, argv, "hvlL:i:", options, NULL)) != -1 ) {
while ( (c = getopt_long(argc, argv, "hvlL:i:t:", options, NULL)) != -1 ) {
switch ( c ) {
case 'h':
usage(EXIT_SUCCESS);
@ -373,6 +397,10 @@ main(int argc, char **argv)
case 'i':
interval = get_uinteger_or_die(optarg);
break;
case 't':
threshold = get_uinteger_or_die(optarg);
break;
}
}
@ -395,8 +423,11 @@ main(int argc, char **argv)
ctx = connect_to_scdaemon();
while ( loop == -1 || loop-- > 0 ) {
n = get_challenge(ctx, random_buffer, nbytes);
write(fd, random_buffer, n);
if ( threshold == 0 || get_available_entropy() < threshold ) {
n = get_challenge(ctx, random_buffer, nbytes);
write(fd, random_buffer, n);
}
if ( loop != 0 )
sleep(interval);

Loading…
Cancel
Save