#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/fcntl.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include "ssh.h"
#include "xmalloc.h"
#include "entropy.h"
#include <openssl/rand.h>
#include <openssl/sha.h>
#ifdef HAVE_FLOATINGPOINT_H
# include <floatingpoint.h>
#endif
void fatal(const char *fmt,...)
{
}
void ssh_debug(const char *fmt,...)
{
}
void error(const char *fmt,...)
{
}
void verbose(const char *fmt,...)
{
}
#ifndef offsetof
# define offsetof(type, member) ((size_t) &((type *)0)->member)
#endif
#define NUM_ENTROPY_RUNS 1
#define SCALE_PER_RUN 10.0
#define MIN_ENTROPY_SOURCES 16
#define WHITESPACE " \t\n"
#ifndef RUSAGE_SELF
# define RUSAGE_SELF 0
#endif
#ifndef RUSAGE_CHILDREN
# define RUSAGE_CHILDREN 0
#endif
#if defined(EGD_SOCKET) || defined(RANDOM_POOL)
#ifdef EGD_SOCKET
int get_random_bytes(unsigned char *buf, int len)
{
int fd;
char msg[2];
struct sockaddr_un addr;
int addr_len;
if (sizeof(EGD_SOCKET) > sizeof(addr.sun_path))
fatal("Random pool path is too long");
if (len > 255)
fatal("Too many bytes to read from EGD");
memset(&addr, '\0', sizeof(addr));
addr.sun_family = AF_UNIX;
strlcpy(addr.sun_path, EGD_SOCKET, sizeof(addr.sun_path));
addr_len = offsetof(struct sockaddr_un, sun_path) + sizeof(EGD_SOCKET);
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd == -1) {
error("Couldn't create AF_UNIX socket: %s", strerror(errno));
return(0);
}
if (connect(fd, (struct sockaddr*)&addr, addr_len) == -1) {
error("Couldn't connect to EGD socket \"%s\": %s",
addr.sun_path, strerror(errno));
close(fd);
return(0);
}
msg[0] = 0x02;
msg[1] = len;
if (atomicio(write, fd, msg, sizeof(msg)) != sizeof(msg)) {
error("Couldn't write to EGD socket \"%s\": %s",
EGD_SOCKET, strerror(errno));
close(fd);
return(0);
}
if (atomicio(read, fd, buf, len) != len) {
error("Couldn't read from EGD socket \"%s\": %s",
EGD_SOCKET, strerror(errno));
close(fd);
return(0);
}
close(fd);
return(1);
}
#else
#ifdef RANDOM_POOL
int get_random_bytes(unsigned char *buf, int len)
{
int random_pool;
random_pool = open(RANDOM_POOL, O_RDONLY);
if (random_pool == -1) {
error("Couldn't open random pool \"%s\": %s",
RANDOM_POOL, strerror(errno));
return(0);
}
if (atomicio(read, random_pool, buf, len) != len) {
error("Couldn't read from random pool \"%s\": %s",
RANDOM_POOL, strerror(errno));
close(random_pool);
return(0);
}
close(random_pool);
return(1);
}
#endif
#endif
void
seed_rng(void)
{
char buf[32];
ssh_debug("Seeding random number generator");
if (!get_random_bytes(buf, sizeof(buf))) {
if (!RAND_status())
fatal("Entropy collection failed and entropy exhausted");
} else {
RAND_add(buf, sizeof(buf), sizeof(buf));
}
memset(buf, '\0', sizeof(buf));
}
void init_rng(void) {}
#else
static int entropy_timeout_current = 1000;
static int prng_seed_saved = 0;
static int prng_initialised = 0;
uid_t original_uid;
typedef struct
{
double rate;
unsigned int badness;
unsigned int sticky_badness;
char *path;
char *args[5];
char *cmdstring;
} entropy_source_t;
double stir_from_system(void);
double stir_from_programs(void);
double stir_gettimeofday(double entropy_estimate);
double stir_clock(double entropy_estimate);
double stir_rusage(int who, double entropy_estimate);
double hash_output_from_command(entropy_source_t *src, char *hash);
entropy_source_t *entropy_sources = NULL;
double
stir_from_system(void)
{
double total_entropy_estimate;
long int i;
total_entropy_estimate = 0;
i = getpid();
RAND_add(&i, sizeof(i), 0.5);
total_entropy_estimate += 0.1;
i = getppid();
RAND_add(&i, sizeof(i), 0.5);
total_entropy_estimate += 0.1;
i = getuid();
RAND_add(&i, sizeof(i), 0.0);
i = getgid();
RAND_add(&i, sizeof(i), 0.0);
total_entropy_estimate += stir_gettimeofday(1.0);
total_entropy_estimate += stir_clock(0.5);
total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0);
return(total_entropy_estimate);
}
double
stir_from_programs(void)
{
int i;
int c;
double entropy_estimate;
double total_entropy_estimate;
char hash[SHA_DIGEST_LENGTH];
total_entropy_estimate = 0;
for(i = 0; i < NUM_ENTROPY_RUNS; i++) {
c = 0;
while (entropy_sources[c].path != NULL) {
if (!entropy_sources[c].badness) {
entropy_estimate = hash_output_from_command(&entropy_sources[c], hash);
entropy_estimate *= entropy_sources[c].rate;
if (entropy_estimate > SHA_DIGEST_LENGTH)
entropy_estimate = SHA_DIGEST_LENGTH;
entropy_estimate /= SCALE_PER_RUN * (i + 1.0);
RAND_add(hash, sizeof(hash), entropy_estimate);
#ifdef DEBUG_ENTROPY
ssh_debug("Got %0.2f bytes of entropy from '%s'", entropy_estimate,
entropy_sources[c].cmdstring);
#endif
total_entropy_estimate += entropy_estimate;
total_entropy_estimate += stir_gettimeofday(0.05);
total_entropy_estimate += stir_clock(0.05);
total_entropy_estimate += stir_rusage(RUSAGE_SELF, 0.1);
total_entropy_estimate += stir_rusage(RUSAGE_CHILDREN, 0.1);
} else {
#ifdef DEBUG_ENTROPY
ssh_debug("Command '%s' disabled (badness %d)",
entropy_sources[c].cmdstring, entropy_sources[c].badness);
#endif
if (entropy_sources[c].badness > 0)
entropy_sources[c].badness--;
}
c++;
}
}
return(total_entropy_estimate);
}
double
stir_gettimeofday(double entropy_estimate)
{
struct timeval tv;
if (gettimeofday(&tv, NULL) == -1)
fatal("Couldn't gettimeofday: %s", strerror(errno));
RAND_add(&tv, sizeof(tv), entropy_estimate);
return(entropy_estimate);
}
double
stir_clock(double entropy_estimate)
{
#ifdef HAVE_CLOCK
clock_t c;
c = clock();
RAND_add(&c, sizeof(c), entropy_estimate);
return(entropy_estimate);
#else
return(0);
#endif
}
double
stir_rusage(int who, double entropy_estimate)
{
#ifdef HAVE_GETRUSAGE
struct rusage ru;
if (getrusage(who, &ru) == -1)
return(0);
RAND_add(&ru, sizeof(ru), entropy_estimate);
return(entropy_estimate);
#else
return(0);
#endif
}
static
int
_get_timeval_msec_difference(struct timeval *t1, struct timeval *t2) {
int secdiff, usecdiff;
secdiff = t2->tv_sec - t1->tv_sec;
usecdiff = (secdiff*1000000) + (t2->tv_usec - t1->tv_usec);
return (int)(usecdiff / 1000);
}
double
hash_output_from_command(entropy_source_t *src, char *hash)
{
static int devnull = -1;
int p[2];
fd_set rdset;
int cmd_eof = 0, error_abort = 0;
struct timeval tv_start, tv_current;
int msec_elapsed = 0;
pid_t pid;
int status;
char buf[16384];
int bytes_read;
int total_bytes_read;
SHA_CTX sha;
if (devnull == -1) {
devnull = open("/dev/null", O_RDWR);
if (devnull == -1)
fatal("Couldn't open /dev/null: %s", strerror(errno));
}
if (pipe(p) == -1)
fatal("Couldn't open pipe: %s", strerror(errno));
(void)gettimeofday(&tv_start, NULL);
switch (pid = fork()) {
case -1:
close(p[0]);
close(p[1]);
fatal("Couldn't fork: %s", strerror(errno));
case 0:
dup2(devnull, STDIN_FILENO);
dup2(p[1], STDOUT_FILENO);
dup2(p[1], STDERR_FILENO);
close(p[0]);
close(p[1]);
close(devnull);
setuid(original_uid);
execv(src->path, (char**)(src->args));
ssh_debug("(child) Couldn't exec '%s': %s", src->cmdstring,
strerror(errno));
_exit(-1);
default:
break;
}
RAND_add(&pid, sizeof(&pid), 0.0);
close(p[1]);
SHA1_Init(&sha);
total_bytes_read = 0;
while (!error_abort && !cmd_eof) {
int ret;
struct timeval tv;
int msec_remaining;
(void) gettimeofday(&tv_current, 0);
msec_elapsed = _get_timeval_msec_difference(&tv_start, &tv_current);
if (msec_elapsed >= entropy_timeout_current) {
error_abort=1;
continue;
}
msec_remaining = entropy_timeout_current - msec_elapsed;
FD_ZERO(&rdset);
FD_SET(p[0], &rdset);
tv.tv_sec = msec_remaining / 1000;
tv.tv_usec = (msec_remaining % 1000) * 1000;
ret = select(p[0]+1, &rdset, NULL, NULL, &tv);
RAND_add(&tv, sizeof(tv), 0.0);
switch (ret) {
case 0:
error_abort = 1;
break;
case 1:
bytes_read = read(p[0], buf, sizeof(buf));
RAND_add(&bytes_read, sizeof(&bytes_read), 0.0);
if (bytes_read == -1) {
error_abort = 1;
break;
} else if (bytes_read) {
SHA1_Update(&sha, buf, bytes_read);
total_bytes_read += bytes_read;
} else {
cmd_eof = 1;
}
break;
case -1:
default:
ssh_debug("Command '%s': select() failed: %s", src->cmdstring,
strerror(errno));
error_abort = 1;
break;
}
}
SHA1_Final(hash, &sha);
close(p[0]);
#ifdef DEBUG_ENTROPY
ssh_debug("Time elapsed: %d msec", msec_elapsed);
#endif
if (waitpid(pid, &status, 0) == -1) {
ssh_debug("Couldn't wait for child '%s' completion: %s", src->cmdstring,
strerror(errno));
return(0.0);
}
RAND_add(&status, sizeof(&status), 0.0);
if (error_abort) {
ssh_debug("Command '%s' timed out", src->cmdstring);
src->sticky_badness *= 2;
src->badness = src->sticky_badness;
return(total_bytes_read);
}
if (WIFEXITED(status)) {
if (WEXITSTATUS(status)==0) {
return(total_bytes_read);
} else {
ssh_debug("Command '%s' exit status was %d", src->cmdstring,
WEXITSTATUS(status));
src->badness = src->sticky_badness = 128;
return (0.0);
}
} else if (WIFSIGNALED(status)) {
ssh_debug("Command '%s' returned on uncaught signal %d !", src->cmdstring,
status);
src->badness = src->sticky_badness = 128;
return(0.0);
} else
return(0.0);
}
int
prng_check_seedfile(char *filename) {
struct stat st;
if (lstat(filename, &st) == -1) {
if (errno != ENOENT)
fatal("Couldn't stat random seed file \"%s\": %s", filename,
strerror(errno));
return(0);
}
if (!S_ISREG(st.st_mode))
fatal("PRNG seedfile %.100s is not a regular file", filename);
if (((st.st_mode & 0177) != 0) || !(st.st_uid == original_uid))
fatal("PRNG seedfile %.100s must be mode 0600, owned by uid %d",
filename, getuid());
return(1);
}
void
prng_write_seedfile(void) {
int fd;
char seed[1024];
char filename[1024];
struct passwd *pw;
if (prng_seed_saved)
return;
setuid(original_uid);
prng_seed_saved = 1;
pw = getpwuid(original_uid);
if (pw == NULL)
fatal("Couldn't get password entry for current user (%i): %s",
original_uid, strerror(errno));
snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
SSH_USER_DIR);
mkdir(filename, 0700);
snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
SSH_PRNG_SEED_FILE);
ssh_debug("writing PRNG seed to file %.100s", filename);
RAND_bytes(seed, sizeof(seed));
prng_check_seedfile(filename);
if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1)
fatal("couldn't access PRNG seedfile %.100s (%.100s)", filename,
strerror(errno));
if (atomicio(write, fd, &seed, sizeof(seed)) != sizeof(seed))
fatal("problem writing PRNG seedfile %.100s (%.100s)", filename,
strerror(errno));
close(fd);
}
void
prng_read_seedfile(void) {
int fd;
char seed[1024];
char filename[1024];
struct passwd *pw;
pw = getpwuid(original_uid);
if (pw == NULL)
fatal("Couldn't get password entry for current user (%i): %s",
original_uid, strerror(errno));
snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir,
SSH_PRNG_SEED_FILE);
ssh_debug("loading PRNG seed from file %.100s", filename);
if (!prng_check_seedfile(filename)) {
verbose("Random seed file not found, creating new");
prng_write_seedfile();
(void)stir_from_system();
(void)stir_from_programs();
return;
}
fd = open(filename, O_RDONLY);
if (fd == -1)
fatal("could not open PRNG seedfile %.100s (%.100s)", filename,
strerror(errno));
if (atomicio(read, fd, &seed, sizeof(seed)) != sizeof(seed)) {
verbose("invalid or short read from PRNG seedfile %.100s - ignoring",
filename);
memset(seed, '\0', sizeof(seed));
}
close(fd);
RAND_add(&seed, sizeof(seed), 0.0);
}
int
prng_read_commands(char *cmdfilename)
{
FILE *f;
char *cp;
char line[1024];
char cmd[1024];
char path[256];
int linenum;
int num_cmds = 64;
int cur_cmd = 0;
double est;
entropy_source_t *entcmd;
f = fopen(cmdfilename, "r");
if (!f) {
fatal("couldn't read entropy commands file %.100s: %.100s",
cmdfilename, strerror(errno));
}
entcmd = (entropy_source_t *)xmalloc(num_cmds * sizeof(entropy_source_t));
memset(entcmd, '\0', num_cmds * sizeof(entropy_source_t));
linenum = 0;
while (fgets(line, sizeof(line), f)) {
int arg;
char *argv;
linenum++;
cp = line + strspn(line, WHITESPACE);
if ((*cp == 0) || (*cp == '#'))
continue;
if (*cp != '"') {
error("bad entropy command, %.100s line %d", cmdfilename,
linenum);
continue;
}
cp = strtok(cp, "\"");
if (cp == NULL) {
error("missing or bad command string, %.100s line %d -- ignored",
cmdfilename, linenum);
continue;
}
strlcpy(cmd, cp, sizeof(cmd));
if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
error("missing command path, %.100s line %d -- ignored",
cmdfilename, linenum);
continue;
}
if (strncmp("undef", cp, 5) == 0)
continue;
strlcpy(path, cp, sizeof(path));
if ((cp = strtok(NULL, WHITESPACE)) == NULL) {
error("missing entropy estimate, %.100s line %d -- ignored",
cmdfilename, linenum);
continue;
}
est = strtod(cp, &argv);
if ((cp = strtok(NULL, WHITESPACE)) != NULL) {
error("garbage at end of line %d in %.100s -- ignored", linenum,
cmdfilename);
continue;
}
entcmd[cur_cmd].cmdstring = xstrdup(cmd);
cp = strtok(cmd, WHITESPACE);
arg = 0;
argv = NULL;
do {
char *s = (char*)xmalloc(strlen(cp) + 1);
strncpy(s, cp, strlen(cp) + 1);
entcmd[cur_cmd].args[arg] = s;
arg++;
} while ((arg < 5) && (cp = strtok(NULL, WHITESPACE)));
if (strtok(NULL, WHITESPACE))
error("ignored extra command elements (max 5), %.100s line %d",
cmdfilename, linenum);
entcmd[cur_cmd].path = xstrdup(path);
entcmd[cur_cmd].rate = est;
entcmd[cur_cmd].sticky_badness = 1;
cur_cmd++;
if (cur_cmd == num_cmds) {
num_cmds *= 2;
entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_source_t));
}
}
memset(&entcmd[cur_cmd], '\0', sizeof(entropy_source_t));
entropy_sources = xrealloc(entcmd, (cur_cmd+1) * sizeof(entropy_source_t));
ssh_debug("Loaded %d entropy commands from %.100s", cur_cmd, cmdfilename);
return (cur_cmd >= MIN_ENTROPY_SOURCES);
}
void
prng_seed_cleanup(void *junk)
{
prng_write_seedfile();
}
void
seed_rng(void)
{
void *old_sigchld_handler;
if (!prng_initialised)
fatal("RNG not initialised");
old_sigchld_handler = signal(SIGCHLD, SIG_DFL);
ssh_debug("Seeded RNG with %i bytes from programs", (int)stir_from_programs());
ssh_debug("Seeded RNG with %i bytes from system calls", (int)stir_from_system());
if (!RAND_status())
fatal("Not enough entropy in RNG");
signal(SIGCHLD, old_sigchld_handler);
if (!RAND_status())
fatal("Couldn't initialise builtin random number generator -- exiting.");
}
void init_rng(void)
{
original_uid = getuid();
if (!prng_read_commands(SSH_PRNG_COMMAND_FILE))
fatal("PRNG initialisation failed -- exiting.");
prng_seed_saved = 0;
prng_read_seedfile();
atexit(prng_write_seedfile);
prng_initialised = 1;
}
#endif