rng-tools-4/0000755000175000017500000000000012202431401011302 5ustar rtgrtgrng-tools-4/fips.c0000664000175000017500000001437412202431225012426 0ustar rtgrtg/* * fips.c -- Performs FIPS 140-1/140-2 RNG tests * * Copyright (C) 2001 Philipp Rumpf * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #define _GNU_SOURCE #ifndef HAVE_CONFIG_H #error Invalid or missing autoconf build environment #endif #include "rng-tools-config.h" #include #include #include "fips.h" /* * Names for the FIPS tests, and bitmask */ const char *fips_test_names[N_FIPS_TESTS] = { "FIPS 140-2(2001-10-10) Monobit", "FIPS 140-2(2001-10-10) Poker", "FIPS 140-2(2001-10-10) Runs", "FIPS 140-2(2001-10-10) Long run", "FIPS 140-2(2001-10-10) Continuous run" }; const unsigned int fips_test_mask[N_FIPS_TESTS] = { FIPS_RNG_MONOBIT, FIPS_RNG_POKER, FIPS_RNG_RUNS, FIPS_RNG_LONGRUN, FIPS_RNG_CONTINUOUS_RUN }; /* These are the startup tests suggested by the FIPS 140-1 spec section * 4.11.1 (http://csrc.nist.gov/fips/fips1401.htm), and updated by FIPS * 140-2 4.9, errata of 2001-10-10. FIPS 140-2, errata of 2002-12-03 * removed all requirements for non-deterministic RNGs, and thus most of * the tests we need are not mentioned in FIPS 140-2 anymore. We also * implement FIPS 140-1 4.11.2/FIPS 140-2 4.9 Continuous Run test. * * The Monobit, Poker, Runs, and Long Runs tests are implemented below. * This test must be run at periodic intervals to verify data is * sufficiently random. If the tests are failed the RNG module shall * no longer submit data to the entropy pool, but the tests shall * continue to run at the given interval. If at a later time the RNG * passes all tests it shall be re-enabled for the next period. * * The reason for this is that it is not unlikely that at some time * during normal operation one of the tests will fail. This does not * necessarily mean the RNG is not operating properly, it is just a * statistically rare event. In that case we don't want to forever * disable the RNG, we will just leave it disabled for the period of * time until the tests are rerun and passed. * * For the continuous run test, we need to check all bits of data, so * "periodic" above shall be read as "for every back-to-back block of * 20000 bits". We verify 32 bits to accomodate the AMD TRNG, and * to reduce false positives with other TRNGs. */ /* * fips_test_store - store 8 bits of entropy in FIPS * internal test data pool */ static void fips_test_store(fips_ctx_t *ctx, unsigned int rng_data) { int j; ctx->poker[rng_data >> 4]++; ctx->poker[rng_data & 15]++; /* Note in the loop below rlength is always one less than the actual run length. This makes things easier. */ for (j = 7; j >= 0; j--) { ctx->ones += ctx->current_bit = ((rng_data >> j) & 1); if (ctx->current_bit != ctx->last_bit) { /* If runlength is 1-6 count it in correct bucket. 0's go in runs[0-5] 1's go in runs[6-11] hence the 6*current_bit below */ if (ctx->rlength < 5) { ctx->runs[ctx->rlength + (6 * ctx->current_bit)]++; } else { ctx->runs[5 + (6 * ctx->current_bit)]++; } /* Check if we just failed longrun test */ if (ctx->rlength >= 25) ctx->longrun = 1; ctx->rlength = 0; /* flip the current run type */ ctx->last_bit = ctx->current_bit; } else { ctx->rlength++; } } } int fips_run_rng_test (fips_ctx_t *ctx, const void *buf) { int i, j; int rng_test = 0; unsigned char *rngdatabuf; if (!ctx) return -1; if (!buf) return -1; rngdatabuf = (unsigned char *)buf; for (i=0; ilast32) rng_test |= FIPS_RNG_CONTINUOUS_RUN; ctx->last32 = new32; fips_test_store(ctx, rngdatabuf[i]); fips_test_store(ctx, rngdatabuf[i+1]); fips_test_store(ctx, rngdatabuf[i+2]); fips_test_store(ctx, rngdatabuf[i+3]); } /* add in the last (possibly incomplete) run */ if (ctx->rlength < 5) ctx->runs[ctx->rlength + (6 * ctx->current_bit)]++; else { ctx->runs[5 + (6 * ctx->current_bit)]++; if (ctx->rlength >= 25) rng_test |= FIPS_RNG_LONGRUN; } if (ctx->longrun) { rng_test |= FIPS_RNG_LONGRUN; ctx->longrun = 0; } /* Ones test */ if ((ctx->ones >= 10275) || (ctx->ones <= 9725)) rng_test |= FIPS_RNG_MONOBIT; /* Poker calcs */ for (i = 0, j = 0; i < 16; i++) j += ctx->poker[i] * ctx->poker[i]; /* 16/5000*1563176-5000 = 2.1632 */ /* 16/5000*1576928-5000 = 46.1696 */ if ((j > 1576928) || (j < 1563176)) rng_test |= FIPS_RNG_POKER; if ((ctx->runs[0] < 2315) || (ctx->runs[0] > 2685) || (ctx->runs[1] < 1114) || (ctx->runs[1] > 1386) || (ctx->runs[2] < 527) || (ctx->runs[2] > 723) || (ctx->runs[3] < 240) || (ctx->runs[3] > 384) || (ctx->runs[4] < 103) || (ctx->runs[4] > 209) || (ctx->runs[5] < 103) || (ctx->runs[5] > 209) || (ctx->runs[6] < 2315) || (ctx->runs[6] > 2685) || (ctx->runs[7] < 1114) || (ctx->runs[7] > 1386) || (ctx->runs[8] < 527) || (ctx->runs[8] > 723) || (ctx->runs[9] < 240) || (ctx->runs[9] > 384) || (ctx->runs[10] < 103) || (ctx->runs[10] > 209) || (ctx->runs[11] < 103) || (ctx->runs[11] > 209)) { rng_test |= FIPS_RNG_RUNS; } /* finally, clear out FIPS variables for start of next run */ memset (ctx->poker, 0, sizeof (ctx->poker)); memset (ctx->runs, 0, sizeof (ctx->runs)); ctx->ones = 0; ctx->rlength = -1; ctx->current_bit = 0; return rng_test; } void fips_init(fips_ctx_t *ctx, unsigned int last32) { if (ctx) { memset (ctx->poker, 0, sizeof (ctx->poker)); memset (ctx->runs, 0, sizeof (ctx->runs)); ctx->longrun = 0; ctx->ones = 0; ctx->rlength = -1; ctx->current_bit = 0; ctx->last_bit = 0; ctx->last32 = last32; } } rng-tools-4/rngd_rdrand.c0000664000175000017500000001066212202431225013745 0ustar rtgrtg/* * Copyright (c) 2012, Intel Corporation * Authors: Richard B. Hill , * H. Peter Anvin * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #define _GNU_SOURCE #ifndef HAVE_CONFIG_H #error Invalid or missing autoconf build environment #endif #include "rng-tools-config.h" #include #include #include #include #include #include #include #include #include #include #include "rngd.h" #include "fips.h" #include "exits.h" #include "rngd_entsource.h" #if defined(__i386__) || defined(__x86_64__) /* Struct for CPUID return values */ struct cpuid { uint32_t eax, ecx, edx, ebx; }; /* Get data from RDRAND */ extern int x86_rdrand_nlong(void *ptr, size_t count); /* Conditioning RDRAND for seed-grade entropy */ extern void x86_aes_mangle(void *data, void *state); /* Checking eflags to confirm cpuid instruction available */ /* Only necessary for 32 bit processors */ #if defined (__i386__) static int x86_has_eflag(uint32_t flag) { uint32_t f0, f1; asm("pushfl ; " "pushfl ; " "popl %0 ; " "movl %0,%1 ; " "xorl %2,%1 ; " "pushl %1 ; " "popfl ; " "pushfl ; " "popl %1 ; " "popfl" : "=&r" (f0), "=&r" (f1) : "ri" (flag)); return !!((f0^f1) & flag); } #endif /* Calling cpuid instruction to verify rdrand capability */ static void cpuid(unsigned int leaf, unsigned int subleaf, struct cpuid *out) { #ifdef __i386__ /* %ebx is a forbidden register if we compile with -fPIC or -fPIE */ asm volatile("movl %%ebx,%0 ; cpuid ; xchgl %%ebx,%0" : "=r" (out->ebx), "=a" (out->eax), "=c" (out->ecx), "=d" (out->edx) : "a" (leaf), "c" (subleaf)); #else asm volatile("cpuid" : "=b" (out->ebx), "=a" (out->eax), "=c" (out->ecx), "=d" (out->edx) : "a" (leaf), "c" (subleaf)); #endif } /* Read data from the drng in chunks of 128 bytes for AES scrambling */ #define CHUNK_SIZE (16*8) static unsigned char iv_buf[CHUNK_SIZE] __attribute__((aligned(128))); int xread_drng(void *buf, size_t size, struct rng *ent_src) { char *p = buf; size_t chunk; const int rdrand_round_count = 512; unsigned char tmp[CHUNK_SIZE] __attribute__((aligned(128))); int i; while (size) { for (i = 0; i < rdrand_round_count; i++) { if (!x86_rdrand_nlong(tmp, CHUNK_SIZE/sizeof(long))) { message(LOG_DAEMON|LOG_ERR, "read error\n"); return -1; } x86_aes_mangle(tmp, iv_buf); } chunk = (sizeof(tmp) > size) ? size : sizeof(tmp); memcpy(p, tmp, chunk); p += chunk; size -= chunk; } return 0; } /* * Confirm RDRAND capabilities for drng entropy source */ int init_drng_entropy_source(struct rng *ent_src) { struct cpuid info; /* We need RDRAND and AESni */ const uint32_t need_features_ecx1 = (1 << 30) | (1 << 25); #if defined(__i386__) if (!x86_has_eflag(1 << 21)) return 1; /* No CPUID instruction */ #endif cpuid(0, 0, &info); if (info.eax < 1) return 1; cpuid(1, 0, &info); if ((info.ecx & need_features_ecx1) != need_features_ecx1) return 1; /* Initialize the IV buffer */ if (!x86_rdrand_nlong(iv_buf, CHUNK_SIZE/sizeof(long))) return 1; src_list_add(ent_src); /* Bootstrap FIPS tests */ ent_src->fipsctx = malloc(sizeof(fips_ctx_t)); fips_init(ent_src->fipsctx, 0); return 0; } #else /* Not i386 or x86-64 */ int init_drng_entropy_source(struct rng *ent_src) { (void)ent_src; return 1; } int xread_drng(void *buf, size_t size, struct rng *ent_src) { (void)buf; (void)size; (void)ent_src; return -1; } #endif /* Not i386 or x86-64 */ rng-tools-4/rngd.h0000664000175000017500000000372712202431225012424 0ustar rtgrtg/* * rngd.h -- rngd globals * * Copyright (C) 2001 Philipp Rumpf * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef RNGD__H #define RNGD__H #define _GNU_SOURCE #include "rng-tools-config.h" #include #include #include #include #include #include "fips.h" enum { MAX_RNG_FAILURES = 25, RNG_OK_CREDIT = 1000, /* ~1:1250 false positives */ }; /* Command line arguments and processing */ struct arguments { char *random_name; char *pid_file; int random_step; int fill_watermark; bool quiet; bool verbose; bool daemon; bool enable_drng; bool enable_tpm; }; extern struct arguments *arguments; /* structures to store rng information */ struct rng { char *rng_name; int rng_fd; bool disabled; int failures; int success; int (*xread) (void *buf, size_t size, struct rng *ent_src); fips_ctx_t *fipsctx; struct rng *next; }; /* Background/daemon mode */ extern bool am_daemon; /* True if we went daemon */ /* * Routines and macros */ #define message(priority,fmt,args...) do { \ if (am_daemon) { \ syslog((priority), fmt, ##args); \ } else { \ fprintf(stderr, fmt, ##args); \ fprintf(stderr, "\n"); \ } \ } while (0) extern void src_list_add(struct rng *ent_src); extern int write_pid_file(const char *pid_fn); #endif /* RNGD__H */ rng-tools-4/rngd_entsource.h0000664000175000017500000000313012202431225014477 0ustar rtgrtg/* * rngd_source.h -- Entropy source and conditioning * * Copyright (C) 2001 Philipp Rumpf * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef RNGD_ENTSOURCE__H #define RNGD_ENTSOURCE__H #include "rng-tools-config.h" #include #include /* Logic and contexts */ extern fips_ctx_t fipsctx; /* Context for the FIPS tests */ extern fips_ctx_t tpm_fipsctx; /* Context for the tpm FIPS tests */ /* * Initialize entropy source and entropy conditioning * * sourcedev is the path to the entropy source */ extern int init_entropy_source(struct rng *); extern int init_drng_entropy_source(struct rng *); extern int init_tpm_entropy_source(struct rng *); /* Read data from the entropy source */ extern int xread(void *buf, size_t size, struct rng *ent_src); extern int xread_drng(void *buf, size_t size, struct rng *ent_src); extern int xread_tpm(void *buf, size_t size, struct rng *ent_src); #endif /* RNGD_ENTSOURCE__H */ rng-tools-4/Makefile.am0000664000175000017500000000073012202425744013355 0ustar rtgrtg## ## Toplevel Makefile.am for rng-tools ## SUBDIRS = contrib sbin_PROGRAMS = rngd bin_PROGRAMS = rngtest man_MANS = rngd.8 rngtest.1 noinst_LIBRARIES = librngd.a rngd_SOURCES = rngd.h rngd.c rngd_entsource.h rngd_entsource.c \ rngd_linux.h rngd_linux.c util.c \ rngd_rdrand.c rdrand_asm.S rngd_LDADD = librngd.a rngtest_SOURCES = exits.h stats.h stats.c rngtest.c rngtest_LDADD = librngd.a librngd_a_SOURCES = fips.h fips.c EXTRA_DIST = autogen.sh rng-tools-4/exits.h0000664000175000017500000000221312202431225012613 0ustar rtgrtg/* * exits.h -- Exit status * * Copyright (C) 2004 Henrique M. Holschuh * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef EXITS__H #define EXITS__H /* Exit status */ #define EXIT_FAIL 1 /* Exit due to error */ #define EXIT_USAGE 10 /* Exit due to user error */ #define EXIT_IOERR 11 /* Exit due to I/O error */ #define EXIT_OSERR 12 /* Exit due to operating system error, resource starvation, or another non-app error */ #endif /* EXITS__H */ rng-tools-4/rngd_linux.c0000664000175000017500000000651212202431225013631 0ustar rtgrtg/* * rngd_linux.c -- Entropy sink for the Linux Kernel (/dev/random) * * Copyright (C) 2001 Philipp Rumpf * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #define _GNU_SOURCE #ifndef HAVE_CONFIG_H #error Invalid or missing autoconf build environment #endif #include "rng-tools-config.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "rngd.h" #include "fips.h" #include "exits.h" #include "rngd_linux.h" extern struct rng *rng_list; /* Kernel output device */ static int random_fd; /* * Get the default watermark */ int default_watermark(void) { char psbuf[64], *p; unsigned long ps; FILE *f; size_t l; unsigned int wm = 2048; /* Default guess */ f = fopen("/proc/sys/kernel/random/poolsize", "r"); if (!f) goto err; l = fread(psbuf, 1, sizeof psbuf, f); if (ferror(f) || !feof(f) || l == 0) goto err; if (psbuf[l-1] != '\n') goto err; psbuf[l-1] = '\0'; ps = strtoul(psbuf, &p, 0); if (*p) goto err; wm = ps*3/4; err: if (f) fclose(f); return wm; } /* * Initialize the interface to the Linux Kernel * entropy pool (through /dev/random) * * randomdev is the path to the random device */ void init_kernel_rng(const char* randomdev) { FILE *f; int err; random_fd = open(randomdev, O_RDWR); if (random_fd == -1) { message(LOG_DAEMON|LOG_ERR, "can't open %s: %s", randomdev, strerror(errno)); exit(EXIT_USAGE); } f = fopen("/proc/sys/kernel/random/write_wakeup_threshold", "w"); if (!f) { err = 1; } else { fprintf(f, "%u\n", arguments->fill_watermark); /* Note | not || here... we always want to close the file */ err = ferror(f) | fclose(f); } if (err) { message(LOG_DAEMON|LOG_WARNING, "unable to adjust write_wakeup_threshold: %s", strerror(errno)); } } void random_add_entropy(void *buf, size_t size) { struct { int ent_count; int size; unsigned char data[size]; } entropy; entropy.ent_count = size * 8; entropy.size = size; memcpy(entropy.data, buf, size); if (ioctl(random_fd, RNDADDENTROPY, &entropy) != 0) { message(LOG_DAEMON|LOG_ERR, "RNDADDENTROPY failed: %s\n", strerror(errno)); exit(1); } } void random_sleep(void) { struct pollfd pfd = { fd: random_fd, events: POLLOUT, }; poll(&pfd, 1, -1); } void src_list_add(struct rng *ent_src) { if (rng_list) { struct rng *iter; iter = rng_list; while (iter->next) { iter = iter->next; } iter->next = ent_src; } else { rng_list = ent_src; } } rng-tools-4/stats.h0000664000175000017500000000425312202431225012623 0ustar rtgrtg/* * stats.h -- Statistics helpers * * Copyright (C) 2004 Henrique M. Holschuh * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef STATS__H #define STATS__H #include #include /* Min-Max stat */ struct rng_stat { uint64_t max; /* Highest value seen */ uint64_t min; /* Lowest value seen */ uint64_t num_samples; /* Number of samples */ uint64_t sum; /* Sum of all samples */ }; /* Sets a prefix for all stat dumps. Maximum length is 19 chars */ extern void set_stat_prefix(const char* prefix); /* Computes elapsed time in microseconds */ extern uint64_t elapsed_time(struct timeval *start, struct timeval *stop); /* Updates min-max stat */ extern void update_stat(struct rng_stat *stat, uint64_t value); /* Updates min-max microseconds timer stat */ #define update_usectimer_stat(STAT, START, STOP) \ update_stat(STAT, elapsed_time(START, STOP)) /* * The following functions format a stat dump on buf, and * return a pointer to the start of buf */ /* Dump simple counter */ extern char *dump_stat_counter(char *buf, int size, const char *msg, uint64_t value); /* Dump min-max time stat */ extern char *dump_stat_stat(char *buf, int size, const char *msg, const char *unit, struct rng_stat *stat); /* * Dump min-max speed stat, base time unit is a microsecond */ extern char *dump_stat_bw(char *buf, int size, const char *msg, const char *unit, struct rng_stat *stat, uint64_t blocksize); #endif /* STATS__H */ rng-tools-4/.gitignore0000664000175000017500000000034512202425744013313 0ustar rtgrtg*.o Makefile Makefile.in INSTALL missing depcomp install-sh stamp-h1 config.* aclocal.m4 configure *.tar.gz push librngd.a rng-tools-config.h* rng-tools-config.h.in rngd rngd.8 rngtest rngtest.1 .dotest autom4te.cache .deps rng-tools-4/AUTHORS0000664000175000017500000000013312202425744012366 0ustar rtgrtgPhilipp Rumpf Jeff Garzik Henrique de Moraes Holschuh rng-tools-4/fips.h0000664000175000017500000000477212202431225012434 0ustar rtgrtg/* * fips.h -- Performs FIPS 140-1/140-2 tests for RNGs * * Copyright (C) 2001 Philipp Rumpf * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef FIPS__H #define FIPS__H /* Size of a FIPS test buffer, do not change this */ #define FIPS_RNG_BUFFER_SIZE 2500 /* Context for running FIPS tests */ struct fips_ctx { int poker[16], runs[12]; int ones, rlength, current_bit, last_bit, longrun; unsigned int last32; }; typedef struct fips_ctx fips_ctx_t; /* Initializes the context for FIPS tests. last32 contains * 32 bits of RNG data to init the continuous run test */ extern void fips_init(fips_ctx_t *ctx, unsigned int last32); /* * Return values for fips_run_rng_test. These values are OR'ed together * for all tests that failed. */ #define FIPS_RNG_MONOBIT 0x0001 /* FIPS 140-2 2001-10-10 monobit */ #define FIPS_RNG_POKER 0x0002 /* FIPS 140-2 2001-10-10 poker */ #define FIPS_RNG_RUNS 0x0004 /* FIPS 140-2 2001-10-10 runs */ #define FIPS_RNG_LONGRUN 0x0008 /* FIPS 140-2 2001-10-10 long run */ #define FIPS_RNG_CONTINUOUS_RUN 0x0010 /* FIPS 140-2 continuous run */ /* * Names for the FIPS tests, and bitmask */ #define N_FIPS_TESTS 5 extern const char *fips_test_names[N_FIPS_TESTS]; extern const unsigned int fips_test_mask[N_FIPS_TESTS]; /* * Runs the FIPS 140-1 4.11.1 and 4.11.2 tests, as updated by * FIPS 140-2 4.9, errata from 2001-10-10 (which set more strict * intervals for the tests to pass), on a buffer of size * FIPS_RNG_BUFFER_SIZE, using the given context. * * FIPS 140-2, errata of 2002-12-03 removed tests for non-deterministic * RNGs, other than Continuous Run test. * * This funtion returns 0 if all tests passed, or a bitmask * with bits set for every test that failed. * * It returns -1 if either fips_ctx or buf is NULL. */ extern int fips_run_rng_test(fips_ctx_t *ctx, const void *buf); #endif /* FIPS__H */ rng-tools-4/LICENSE0000664000175000017500000000014712202425744012330 0ustar rtgrtgrng-tools are available under the terms of the GNU Public License version 2. See COPYING for details. rng-tools-4/rngd.8.in0000664000175000017500000000622412202431225012744 0ustar rtgrtg.\" Copyright (C) 2001 Jeff Garzik -- jgarzik@pobox.com .\" .TH RNGD 8 "March 2001" "@PACKAGE@ @VERSION@" .SH NAME rngd \- Check and feed random data from hardware device to kernel random device .SH SYNOPSIS .B rngd [\fB\-b\fR, \fB\-\-background\fR] [\fB\-f\fR, \fB\-\-foreground\fR] [\fB\-o\fR, \fB\-\-random-device=\fIfile\fR] [\fB\-p\fR, \fB\-\-pid-file=\fIfile\fR] [\fB\-r\fR, \fB\-\-rng-device=\fIfile\fR] [\fB\-s\fR, \fB\-\-random-step=\fInnn\fR] [\fB\-W\fR, \fB\-\-fill-watermark=\fInnn\fR] [\fB\-d\fR, \fB\-\-no-drng=\fI1|0\fR] [\fB\-n\fR, \fB\-\-no-tpm=\fI1|0\fR] [\fB\-q\fR, \fB\-\-quiet\fR] [\fB\-v\fR, \fB\-\-verbose\fR] [\fB\-?\fR, \fB\-\-help\fR] [\fB\-V\fR, \fB\-\-version\fR] .RI .SH DESCRIPTION This daemon feeds data from a random number generator to the kernel's random number entropy pool, after first checking the data to ensure that it is properly random. .PP The \fB\-f\fR or \fB\-\-foreground\fR options can be used to tell \fBrngd\fR to avoid forking on startup. This is typically used for debugging. The \fB\-b\fR or \fB\-\-background\fR options, which fork and put \fBrngd\fR into the background automatically, are the default. .PP The \fB\-r\fR or \fB\-\-rng-device\fR options can be used to select an alternate source of input, besides the default /dev/hwrandom. The \fB\-o\fR or \fB\-\-random-device\fR options can be used to select an alternate entropy output device, besides the default /dev/random. Note that this device must support the Linux kernel /dev/random ioctl API. .PP FIXME: document random-step and timeout .SH OPTIONS .TP \fB\-b\fR, \fB\-\-background\fR Become a daemon (default) .TP \fB\-f\fR, \fB\-\-foreground\fR Do not fork and become a daemon .TP \fB\-p\fI file\fR, \fB\-\-pid-file=\fIfile\fR File used for recording daemon PID, and multiple exclusion (default: /var/run/rngd.pid) .TP \fB\-o\fI file\fR, \fB\-\-random-device=\fIfile\fR Kernel device used for random number output (default: /dev/random) .TP \fB\-r\fI file\fR, \fB\-\-rng-device=\fIfile\fR Kernel device used for random number input (default: /dev/hwrandom) .TP \fB\-s\fI nnn\fR, \fB\-\-random-step=\fInnn\fR Number of bytes written to random-device at a time (default: 64) .TP \fB\-W\fI n\fR, \fB\-\-fill\-watermark=\fInnn\fR Once we start doing it, feed entropy to \fIrandom-device\fR until at least \fIfill-watermark\fR bits of entropy are available in its entropy pool (default: 2048). Setting this too high will cause \fIrngd\fR to dominate the contents of the entropy pool. Low values will hurt system performance during entropy starves. Do not set \fIfill-watermark\fR above the size of the entropy pool (usually 4096 bits). .TP \fB\-d\fI 1|0\fR, \fB\-\-no-drng=\fI1|0\fR Do not use drng as a source of random number input (default:0) .TP \fB\-n\fI 1|0\fR, \fB\-\-no-tpm=\fI1|0\fR Do not use tpm as a source of random number input (default:0) .TP \fB\-q\fR, \fB\-\-quiet\fR Suppress error messages .TP \fB\-v\fR, \fB\-\-verbose\fR Report available entropy sources .TP \fB\-?\fR, \fB\-\-help\fR Give a short summary of all program options. .TP \fB\-V\fR, \fB\-\-version\fR Print program version .SH AUTHORS Philipp Rumpf .br Jeff Garzik \- jgarzik@pobox.com .br Matt Sottek .br Brad Hill rng-tools-4/rdrand_asm.S0000664000175000017500000001210212202431225013542 0ustar rtgrtg/* * Copyright (c) 2011, Intel Corporation * Authors: Fenghua Yu , * H. Peter Anvin * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #define ENTRY(x) \ .balign 64 ; \ .globl x ; \ x: #define ENDPROC(x) \ .size x, .-x ; \ .type x, @function #define RDRAND_RETRY_LIMIT 10 #if defined(__x86_64__) ENTRY(x86_rdrand_nlong) 1: mov $RDRAND_RETRY_LIMIT, %eax 2: .byte 0x48,0x0f,0xc7,0xf2 /* rdrand %rdx */ jnc 3f mov %rdx, (%rdi) add $8, %rdi sub $1, %esi jnz 1b ret 3: sub $1, %eax rep;nop jnz 2b ret ENDPROC(x86_rdrand_nlong) #define SETPTR(var,ptr) leaq var(%rip),ptr #define PTR0 %rdi #define PTR1 %rsi #define PTR2 %rcx #define NPTR2 1 /* %rcx = %r1, only 0-7 valid here */ #elif defined(__i386__) ENTRY(x86_rdrand_nlong) push %ebp mov %esp, %ebp push %edi movl 8(%ebp), %ecx movl 12(%ebp), %edx 1: mov $RDRAND_RETRY_LIMIT, %eax 2: .byte 0x0f,0xc7,0xf7 /* rdrand %edi */ jnc 3f mov %edi, (%ecx) add $4, %ecx sub $1, %edx jnz 2b pop %edi pop %ebp ret 3: sub $1, %eax rep;nop jnz 2b pop %edi pop %ebp ret ENDPROC(x86_rdrand_nlong) #define SETPTR(var,ptr) movl $(var),ptr #define PTR0 %eax #define PTR1 %edx #define PTR2 %ecx #define NPTR2 1 /* %rcx = %r1 */ #endif #if defined(__i386__) || defined(__x86_64__) ENTRY(x86_aes_mangle) #if defined(__i386__) push %ebp mov %esp, %ebp movl 8(%ebp), %eax movl 12(%ebp), %edx #endif SETPTR(aes_round_keys, PTR2) movdqa (0*16)(PTR0), %xmm0 movdqa (1*16)(PTR0), %xmm1 movdqa (2*16)(PTR0), %xmm2 movdqa (3*16)(PTR0), %xmm3 movdqa (4*16)(PTR0), %xmm4 movdqa (5*16)(PTR0), %xmm5 movdqa (6*16)(PTR0), %xmm6 movdqa (7*16)(PTR0), %xmm7 pxor (0*16)(PTR1), %xmm0 pxor (1*16)(PTR1), %xmm1 pxor (2*16)(PTR1), %xmm2 pxor (3*16)(PTR1), %xmm3 pxor (4*16)(PTR1), %xmm4 pxor (5*16)(PTR1), %xmm5 pxor (6*16)(PTR1), %xmm6 pxor (7*16)(PTR1), %xmm7 .rept 10 .byte 0x66,0x0f,0x38,0xdc,0x00+NPTR2 /* aesenc (PTR2), %xmm0 */ .byte 0x66,0x0f,0x38,0xdc,0x08+NPTR2 /* aesenc (PTR2), %xmm1 */ .byte 0x66,0x0f,0x38,0xdc,0x10+NPTR2 /* aesenc (PTR2), %xmm2 */ .byte 0x66,0x0f,0x38,0xdc,0x18+NPTR2 /* aesenc (PTR2), %xmm3 */ .byte 0x66,0x0f,0x38,0xdc,0x20+NPTR2 /* aesenc (PTR2), %xmm4 */ .byte 0x66,0x0f,0x38,0xdc,0x28+NPTR2 /* aesenc (PTR2), %xmm5 */ .byte 0x66,0x0f,0x38,0xdc,0x30+NPTR2 /* aesenc (PTR2), %xmm6 */ .byte 0x66,0x0f,0x38,0xdc,0x38+NPTR2 /* aesenc (PTR2), %xmm7 */ add $16, PTR2 .endr .byte 0x66,0x0f,0x38,0xdd,0x00+NPTR2 /* aesenclast (PTR2), %xmm0 */ .byte 0x66,0x0f,0x38,0xdd,0x08+NPTR2 /* aesenclast (PTR2), %xmm1 */ .byte 0x66,0x0f,0x38,0xdd,0x10+NPTR2 /* aesenclast (PTR2), %xmm2 */ .byte 0x66,0x0f,0x38,0xdd,0x18+NPTR2 /* aesenclast (PTR2), %xmm3 */ .byte 0x66,0x0f,0x38,0xdd,0x20+NPTR2 /* aesenclast (PTR2), %xmm4 */ .byte 0x66,0x0f,0x38,0xdd,0x28+NPTR2 /* aesenclast (PTR2), %xmm5 */ .byte 0x66,0x0f,0x38,0xdd,0x30+NPTR2 /* aesenclast (PTR2), %xmm6 */ .byte 0x66,0x0f,0x38,0xdd,0x38+NPTR2 /* aesenclast (PTR2), %xmm7 */ movdqa %xmm0, (0*16)(PTR0) movdqa %xmm1, (1*16)(PTR0) movdqa %xmm2, (2*16)(PTR0) movdqa %xmm3, (3*16)(PTR0) movdqa %xmm4, (4*16)(PTR0) movdqa %xmm5, (5*16)(PTR0) movdqa %xmm6, (6*16)(PTR0) movdqa %xmm7, (7*16)(PTR0) movdqa %xmm0, (0*16)(PTR1) movdqa %xmm1, (1*16)(PTR1) movdqa %xmm2, (2*16)(PTR1) movdqa %xmm3, (3*16)(PTR1) movdqa %xmm4, (4*16)(PTR1) movdqa %xmm5, (5*16)(PTR1) movdqa %xmm6, (6*16)(PTR1) movdqa %xmm7, (7*16)(PTR1) #if defined(__i386__) pop %ebp #endif ret ENDPROC(x86_aes_mangle) /* * AES round keys for an arbitrary key: * 00102030405060708090A0B0C0D0E0F0 */ .section ".rodata","a" .balign 16 aes_round_keys: .long 0x00102030, 0x40506070, 0x8090A0B0, 0xC0D0E0F0 .long 0x89D810E8, 0x855ACE68, 0x2D1843D8, 0xCB128FE4 .long 0x4915598F, 0x55E5D7A0, 0xDACA94FA, 0x1F0A63F7 .long 0xFA636A28, 0x25B339C9, 0x40668A31, 0x57244D17 .long 0x24724023, 0x6966B3FA, 0x6ED27532, 0x88425B6C .long 0xC81677BC, 0x9B7AC93B, 0x25027992, 0xB0261996 .long 0xC62FE109, 0xF75EEDC3, 0xCC79395D, 0x84F9CF5D .long 0xD1876C0F, 0x79C4300A, 0xB45594AD, 0xD66FF41F .long 0xFDE3BAD2, 0x05E5D0D7, 0x3547964E, 0xF1FE37F1 .long 0xBD6E7C3D, 0xF2B5779E, 0x0B61216E, 0x8B10B689 .long 0x69C4E0D8, 0x6A7B0430, 0xD8CDB780, 0x70B4C55A .size aes_round_keys, .-aes_round_keys .bss .balign 16 aes_fwd_state: .space 16 .size aes_fwd_state, .-aes_fwd_state #endif /* i386 or x86_64 */ /* * This is necessary to keep the whole executable * from needing a writable stack. */ .section .note.GNU-stack,"",%progbits rng-tools-4/COPYING0000664000175000017500000004311012202431225012342 0ustar rtgrtg GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. rng-tools-4/autogen.sh0000775000175000017500000000027112202425744013322 0ustar rtgrtg#!/bin/sh # You need autoconf 2.5x, preferably 2.57 or later # You need automake 1.7 or later. 1.6 might work. set -e aclocal autoheader automake --gnu --add-missing --copy autoconf rng-tools-4/rngd_linux.h0000664000175000017500000000263112202431225013634 0ustar rtgrtg/* * rngd_linux.h -- Entropy sink for the Linux Kernel (/dev/random) * * Copyright (C) 2001 Philipp Rumpf * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef RNGD_LINUX__H #define RNGD_LINUX__H #include "rng-tools-config.h" #include #include /* The default watermark level for this platform */ extern int default_watermark(void); /* * Initialize the interface to the Linux Kernel * entropy pool (through /dev/random) * * randomdev is the path to the random device */ extern void init_kernel_rng(const char* randomdev); /* Send entropy to the kernel */ extern void random_add_entropy(void *buf, size_t size); /* Sleep until the kernel is hungry for entropy */ extern void random_sleep(void); #endif /* RNGD_LINUX__H */ rng-tools-4/rngd.c0000664000175000017500000002104212202431225012405 0ustar rtgrtg/* * rngd.c -- Random Number Generator daemon * * rngd reads data from a hardware random number generator, verifies it * looks like random data, and adds it to /dev/random's entropy store. * * In theory, this should allow you to read very quickly from * /dev/random; rngd also adds bytes to the entropy store periodically * when it's full, which makes predicting the entropy store's contents * harder. * * Copyright (C) 2001 Philipp Rumpf * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #define _GNU_SOURCE #ifndef HAVE_CONFIG_H #error Invalid or missing autoconf build environment #endif #include "rng-tools-config.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "rngd.h" #include "fips.h" #include "exits.h" #include "rngd_entsource.h" #include "rngd_linux.h" /* * Globals */ /* Background/daemon mode */ bool am_daemon; /* True if we went daemon */ bool server_running = true; /* set to false, to stop daemon */ /* Command line arguments and processing */ const char *argp_program_version = "rngd " VERSION "\n" "Copyright 2001-2004 Jeff Garzik\n" "Copyright (c) 2001 by Philipp Rumpf\n" "This is free software; see the source for copying conditions. There is NO " "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."; const char *argp_program_bug_address = PACKAGE_BUGREPORT; static char doc[] = "Check and feed random data from hardware device to kernel entropy pool.\n"; static struct argp_option options[] = { { "foreground", 'f', 0, 0, "Do not fork and become a daemon" }, { "background", 'b', 0, 0, "Become a daemon (default)" }, { "random-device", 'o', "file", 0, "Kernel device used for random number output (default: /dev/random)" }, { "rng-device", 'r', "file", 0, "Kernel device used for random number input (default: /dev/hwrng)" }, { "pid-file", 'p', "file", 0, "File used for recording daemon PID, and multiple exclusion (default: /var/run/rngd.pid)" }, { "random-step", 's', "nnn", 0, "Number of bytes written to random-device at a time (default: 64)" }, { "fill-watermark", 'W', "n", 0, "Do not stop feeding entropy to random-device until at least n bits of entropy are available in the pool (default: 2048), 0 <= n <= 4096" }, { "quiet", 'q', 0, 0, "Suppress error messages" }, { "verbose" ,'v', 0, 0, "Report available entropy sources" }, { "no-drng", 'd', "1|0", 0, "Do not use drng as a source of random number input (default: 0)" }, { "no-tpm", 'n', "1|0", 0, "Do not use tpm as a source of random number input (default: 0)" }, { 0 }, }; static struct arguments default_arguments = { .random_name = "/dev/random", .pid_file = "/var/run/rngd.pid", .random_step = 64, .daemon = true, .enable_drng = true, .enable_tpm = true, .quiet = false, .verbose = false, }; struct arguments *arguments = &default_arguments; static struct rng rng_default = { .rng_name = "/dev/hwrng", .rng_fd = -1, .xread = xread, }; static struct rng rng_drng = { .rng_name = "drng", .rng_fd = -1, .xread = xread_drng, }; static struct rng rng_tpm = { .rng_name = "/dev/tpm0", .rng_fd = -1, .xread = xread_tpm, }; struct rng *rng_list; /* * command line processing */ static error_t parse_opt (int key, char *arg, struct argp_state *state) { switch(key) { case 'o': arguments->random_name = arg; break; case 'p': arguments->pid_file = arg; break; case 'r': rng_default.rng_name = arg; break; case 'f': arguments->daemon = false; break; case 'b': arguments->daemon = true; break; case 's': if (sscanf(arg, "%i", &arguments->random_step) == 0) argp_usage(state); break; case 'W': { int n; if ((sscanf(arg, "%i", &n) == 0) || (n < 0) || (n > 4096)) argp_usage(state); else arguments->fill_watermark = n; break; } case 'q': arguments->quiet = true; break; case 'v': arguments->verbose = true; break; case 'd': { int n; if ((sscanf(arg,"%i", &n) == 0) || ((n | 1)!=1)) argp_usage(state); else arguments->enable_drng = false; break; } case 'n': { int n; if ((sscanf(arg,"%i", &n) == 0) || ((n | 1)!=1)) argp_usage(state); else arguments->enable_tpm = false; break; } default: return ARGP_ERR_UNKNOWN; } return 0; } static struct argp argp = { options, parse_opt, NULL, doc }; static int update_kernel_random(int random_step, unsigned char *buf, fips_ctx_t *fipsctx_in) { unsigned char *p; int fips; fips = fips_run_rng_test(fipsctx_in, buf); if (fips) return 1; for (p = buf; p + random_step <= &buf[FIPS_RNG_BUFFER_SIZE]; p += random_step) { random_add_entropy(p, random_step); random_sleep(); } return 0; } static void do_loop(int random_step) { unsigned char buf[FIPS_RNG_BUFFER_SIZE]; int retval = 0; int no_work = 0; while (no_work < 100) { struct rng *iter; bool work_done; work_done = false; for (iter = rng_list; iter; iter = iter->next) { int rc; if (!server_running) return; retry_same: if (iter->disabled) continue; /* failed, no work */ retval = iter->xread(buf, sizeof buf, iter); if (retval) continue; /* failed, no work */ work_done = true; rc = update_kernel_random(random_step, buf, iter->fipsctx); if (rc == 0) { iter->success++; if (iter->success >= RNG_OK_CREDIT) { if (iter->failures) iter->failures--; iter->success = 0; } break; /* succeeded, work done */ } iter->failures++; if (iter->failures <= MAX_RNG_FAILURES/4) { /* FIPS tests have false positives */ goto retry_same; } else if (iter->failures >= MAX_RNG_FAILURES) { if (!arguments->quiet) message(LOG_DAEMON|LOG_ERR, "too many FIPS failures, disabling entropy source\n"); iter->disabled = true; } } if (!work_done) no_work++; } if (!arguments->quiet) message(LOG_DAEMON|LOG_ERR, "No entropy sources working, exiting rngd\n"); } static void term_signal(int signo) { server_running = false; } int main(int argc, char **argv) { int rc_rng = 1; int rc_drng = 1; int rc_tpm = 1; int pid_fd = -1; openlog("rngd", 0, LOG_DAEMON); /* Get the default watermark level for this platform */ arguments->fill_watermark = default_watermark(); /* Parsing of commandline parameters */ argp_parse(&argp, argc, argv, 0, 0, arguments); /* Init entropy sources, and open TRNG device */ if (arguments->enable_drng) rc_drng = init_drng_entropy_source(&rng_drng); rc_rng = init_entropy_source(&rng_default); if (arguments->enable_tpm && rc_rng) rc_tpm = init_tpm_entropy_source(&rng_tpm); if (rc_rng && rc_drng && rc_tpm) { if (!arguments->quiet) { message(LOG_DAEMON|LOG_ERR, "can't open any entropy source"); message(LOG_DAEMON|LOG_ERR, "Maybe RNG device modules are not loaded\n"); } return 1; } if (arguments->verbose) { printf("Available entropy sources:\n"); if (!rc_rng) printf("\tIntel/AMD hardware rng\n"); if (!rc_drng) printf("\tDRNG\n"); if (!rc_tpm) printf("\tTPM\n"); } if (rc_rng && (rc_drng || !arguments->enable_drng) && (rc_tpm || !arguments->enable_tpm)) { if (!arguments->quiet) message(LOG_DAEMON|LOG_ERR, "No entropy source available, shutting down\n"); return 1; } /* Init entropy sink and open random device */ init_kernel_rng(arguments->random_name); if (arguments->daemon) { am_daemon = true; if (daemon(0, 0) < 0) { if(!arguments->quiet) fprintf(stderr, "can't daemonize: %s\n", strerror(errno)); return 1; } /* require valid, locked PID file to proceed */ pid_fd = write_pid_file(arguments->pid_file); if (pid_fd < 0) return 1; signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN); signal(SIGINT, term_signal); signal(SIGTERM, term_signal); } do_loop(arguments->random_step); if (pid_fd >= 0) unlink(arguments->pid_file); return 0; } rng-tools-4/README0000664000175000017500000000103612202425744012201 0ustar rtgrtg This is a random number generator daemon. It monitors a hardware random number generator, and supplies entropy from that to the system kernel's /dev/random machinery. It is hoped that future contributions will enable entropy gathering from other sources, such as audio hardware or video hardware or CPU instruction pointers, to provide entropy even in cases where a true hardware RNG is not present. Home page: http://sourceforge.net/projects/gkernel/ GIT repository: git://git.kernel.org/pub/scm/utils/kernel/rng-tools/rng-tools.git rng-tools-4/configure.ac0000664000175000017500000000356712202431225013611 0ustar rtgrtgdnl Process this file with autoconf 2.52+ to produce a configure script. dnl dnl Copyright (C) 2001 Philipp Rumpf dnl Copyright (C) 2004 Henrique de Moraes Holschuh dnl dnl This program is free software; you can redistribute it and/or modify dnl it under the terms of the GNU General Public License as published by dnl the Free Software Foundation; either version 2 of the License, or dnl (at your option) any later version. dnl dnl This program is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the dnl GNU General Public License for more details. dnl dnl You should have received a copy of the GNU General Public License dnl along with this program; if not, write to the Free Software dnl Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA AC_INIT(rng-tools, 4, [Jeff Garzik ]) AC_PREREQ(2.52) AC_CONFIG_SRCDIR([rngd.c]) AM_INIT_AUTOMAKE([gnu]) AC_CONFIG_HEADERS([rng-tools-config.h]) dnl Make sure anyone changing configure.ac/Makefile.am has a clue AM_MAINTAINER_MODE dnl Checks for programs AC_PROG_CC AC_PROG_RANLIB AC_PROG_GCC_TRADITIONAL dnl Checks for header files. dnl AC_HEADER_STDC dnl AC_CHECK_HEADERS(sys/ioctl.h unistd.h) dnl Checks for typedefs, structures, and compiler characteristics. dnl AC_TYPE_SIZE_T dnl AC_TYPE_PID_T dnl ----------------------------- dnl Checks for required libraries dnl ----------------------------- dnl ------------------------------------- dnl Checks for optional library functions dnl ------------------------------------- dnl ----------------- dnl Configure options dnl ----------------- AM_PROG_AS dnl -------------------------- dnl autoconf output generation dnl -------------------------- AC_CONFIG_FILES([Makefile contrib/Makefile rngd.8 rngtest.1]) AC_OUTPUT rng-tools-4/rngtest.1.in0000664000175000017500000000572112202431225013472 0ustar rtgrtg.\" Copyright (c) 2004 Henrique de Moraes Holschuh -- hmh@debian.org .\" .TH RNGTEST 1 "March 2004" "@PACKAGE@ @VERSION@" .SH NAME rngtest \- Check the randomness of data using FIPS 140-2 tests .SH SYNOPSIS .B rngtest [\fB\-c\fR \fIn\fR | \fB\-\-blockcount=\fIn\fR] [\fB\-b\fR \fIn\fR | \fB\-\-blockstats=\fIn\fR] [\fB\-t\fR \fIn\fR | \fB\-\-timedstats=\fIn\fR] [\fB\-p\fR | \fB\-\-pipe\fR] [\fB\-?\fR] [\fB\-\-help\fR] [\fB\-V\fR] [\fB\-\-version\fR] .RI .SH DESCRIPTION \fIrngtest\fR works on blocks of 20000 bits at a time, using the FIPS 140-2 (errata of 2001-10-10) tests to verify the randomness of the block of data. .PP It takes input from \fIstdin\fR, and outputs statistics to \fIstderr\fR, optionally echoing blocks that passed the FIPS tests to \fIstdout\fR (when operating in \fIpipe mode\fR). Errors are sent to \fIstderr\fR. .PP At startup, \fIrngtest\fR will trow away the first 32 bits of data when operating in \fIpipe mode\fR. It will use the next 32 bits of data to bootstrap the FIPS tests (even when not operating in \fIpipe mode\fR). These bits are not tested for randomness. .PP Statistics are dumped to \fIstderr\fR when the program exits. .SH OPTIONS .TP \fB\-p\fR, \fB\-\-pipe\fR Enable \fIpipe mode\fR. All data blocks that pass the FIPS tests are echoed to \fIstdout\fR, and \fIrngtest\fR operates in silent mode. .TP \fB\-c\fR \fIn\fR, \fB\-\-blockcount=\fIn\fR (default: 0) Exit after processing n input blocks, if n is not zero. .TP \fB\-b\fR \fIn\fR, \fB\-\-blockstats=\fIn\fR (default: 0) Dump statistics every n blocks, if n is not zero. .TP \fB\-t\fR \fIn\fR, \fB\-\-timedstats=\fIn\fR (default: 0) Dump statistics every n secods, if n is not zero. .TP \fB\-?\fR, \fB\-\-help\fR Give a short summary of all program options. .TP \fB\-V\fR, \fB\-\-version\fR Print program version .SH STATISTICS \fIrngtest\fR will dump statistics to \fIstderr\fR when it exits, and when told to by \fIblockstats\fR or \fItimedstats\fR. .PP \fBFIPS 140-2 successes\fR and \fBFIPS 140-2 failures\fR counts the number of 20000-bit blocks either accepted or rejected by the FIPS 140-2 tests. The other statistics show a breakdown of the FIPS 140-2 failures by FIPS 140-2 test. See the FIPS 140-2 document for more information (note that these tests are defined on FIPS 140-1 and FIPS 140-2 errata of 2001-10-10. They were removed in FIPS 140-2 errata of 2002-12-03). .PP The speed statistics are taken for every 20000-bit block trasferred or processed. .SH EXIT STATUS .TP \fB0\fR if no errors happen, and no blocks fail the FIPS tests. .TP \fB1\fR if no errors happen, but at least one block fails the FIPS tests. .TP \fB10\fR if there are problems with the parameters. .TP \fB11\fR if an input/output error happens. .TP \fB12\fR if an operating system or resource starvation error happens. .SH SEE ALSO random(4), rngd(8) .TP FIPS PUB 140-2 Security Requirements for Cryptographic Modules, NIST, http://csrc.nist.gov/cryptval/140-2.htm .SH AUTHORS Henrique de Moraes Holschuh rng-tools-4/util.c0000664000175000017500000000436112202425744012446 0ustar rtgrtg /* * Copyright 2009 Red Hat, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #define _GNU_SOURCE #ifndef HAVE_CONFIG_H #error Invalid or missing autoconf build environment #endif #include "rng-tools-config.h" #include #include #include #include #include #include "rngd.h" int write_pid_file(const char *pid_fn) { char str[32], *s; size_t bytes; int fd; struct flock lock; int err; /* build file data */ sprintf(str, "%u\n", (unsigned int) getpid()); /* open non-exclusively (works on NFS v2) */ fd = open(pid_fn, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); if (fd < 0) { err = errno; message(LOG_DAEMON|LOG_ERR, "Cannot open PID file %s: %s", pid_fn, strerror(err)); return -err; } /* lock */ memset(&lock, 0, sizeof(lock)); lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; if (fcntl(fd, F_SETLK, &lock) != 0) { err = errno; if (err == EAGAIN) { message(LOG_DAEMON|LOG_ERR, "PID file %s is already locked", pid_fn); } else { message(LOG_DAEMON|LOG_ERR, "Cannot lock PID file %s: %s", pid_fn, strerror(err)); } close(fd); return -err; } /* write file data */ bytes = strlen(str); s = str; while (bytes > 0) { ssize_t rc = write(fd, s, bytes); if (rc < 0) { err = errno; message(LOG_DAEMON|LOG_ERR, "PID number write failed: %s", strerror(err)); goto err_out; } bytes -= rc; s += rc; } /* make sure file data is written to disk */ if (fsync(fd) < 0) { err = errno; message(LOG_DAEMON|LOG_ERR, "PID file fsync failed: %s", strerror(err)); goto err_out; } return fd; err_out: unlink(pid_fn); close(fd); return -err; } rng-tools-4/ChangeLog0000664000175000017500000001217012202425744013074 0ustar rtgrtgTue May 09 2004 Henrique de Moraes Holschuh * rngd.h, rngd.c, rngd_linux.c, rngd.8.in: Let the user set the fill watermark explicitly, using the new -W command line option. This gets rid of RNDGETPOOL usage, and of a hardcoded (yuck) setting of 50%. This change will make rngd work right with 2.6 kernels. Thu Apr 15 2004 Jeff Garzik * Makefile.am, configure.ac: put common code in a lib Tue Apr 6 2004 Henrique de Moraes Holschuh * rngd.c, rngtest.c: Add Copyright and license notices to --version output, as per the GNU guidelines; Improve --help output a little. * rngtest.c: Cleanup logging, and exit with status 1 when input drains before the first block is tested. * rngtest.1.in: Minor text change. Preparatory cleanup for merging the multithreaded code later: * rngd.c: split globals to rngd.h; split linux /dev/random functionality to rngd_linux.c; split entropy source (/dev/hwrandom) functionality to rngd_entsource.c. * rngd.h, rngd_linux.h, rngd_linux.c, rngd_entsource.h, rngd_entsource.c: add Tue Apr 6 2004 Jeff Garzik * Release version 1.1. Fri Apr 5 2004 Henrique de Moraes Holschuh Add rngtest application: * Makefile.am: build rngtest. * configure.ac: process rngtest.1.in. * stats.h/stats.c: add. Statistics based on ideas from mtrngd.cpp by Martin Peck * exits.h: add. * rngtest.c: add. * contrib/Makefile.am: remove rngtest.c. * contrib/rngtest.c: remove. * AUTHORS: add myself Fri Apr 5 2004 Henrique de Moraes Holschuh * rngd.c: use C99 initializers syntax, and stop compilation if build env. is incomplete * fips.c, fips.h: s/FIPS_TESTS/N_FIPS_TESTS/ and remove uneeded includes * fips.c: reword error message when build env. is incomplete, and also reorder some includes * AUTHORS, configure.ac, fips.c, fips.h, rngd.c, rngd.8.in: Update Jeff Garzik's email address, remove outdated email address for Philipp Rumpf, on request by Jeff Garzik. * configure.ac, rngd.c: Change bugreport address to Jeff Garzik's. Fri Apr 4 2004 Henrique de Moraes Holschuh * Makefile.am: Add header and CVS Id tag; Do some cosmetic reformating; Add rngd_SOURCES. * rngd.c: move all FIPS test code to fips.h/fips.c * fips.h, fips.c: add. + Update comments with more FIPS 140-2 trivia. + Use a context structure to hold the FIPS test data. + Implement FIPS 140-2 4.9 Continuous Run test. + Add constants with the test names and bitmask for easier statistic reporting later. Fri Apr 3 2004 Henrique de Moraes Holschuh * autogen.sh: Add comments with the required versions of the tools. Call aclocal before autoheader. Use --copy for automake invocation. Identify as version 1.1-devel. * configure.in: rename to configure.ac * configure.ac: Add GPL header. Convert to autoconf 2.50 macros, enable AM_MAINTAINER_MODE and disable useless cross-platform compatiblilty glue that isn't used anywere * acconfig.h: remove * .cvsignore: update for new autotools Sat Jul 5 2003 Jeff Garzik * contrib/rngtest.c, rngd.8.in: s/intel_rng/hwrandom/ Noticed by Olivier NICOLAS. Sat Jul 5 2003 Sami Farin "updated" to FIPS140-2 standard, it has a bit more strict constraints on randomness.. about one out of 1000 blocks read from /dev/urandom causes a failure. also a bugfix: checks for EINTR in xread (maybe not necessary with i810 driver?) Sat Jul 5 2003 Jeff Garzik Rename to rng-tools, release version 1.0. Rename input device to /dev/hwrandom in code and docs. Rename config.h to rng-tools-config.h. Tue Mar 27 2001 Jeff Garzik * rngd.c: Include config.h, pick up VERSION from configure.in, via config.h. Mon Mar 26 2001 Philipp Rumpf * rngd.c: fail before the daemon() call if we can't open /dev/random or /dev/intel_rng Mon Mar 26 2001 Philipp Rumpf * rngd.c: bugfixes, allow --timeout=0 to disable periodical writes. Fri Mar 23 2001 Jeff Garzik * rngd.c: Remove unused var. Include stdlib.h for exit(3). Fri Mar 23 2001 Philipp Rumpf * rngd.c: fix argp_parse arguments Fri Mar 23 2001 Jeff Garzik * configure.in: Change version in cvs * Makefile.am, configure.in, rngd.8.in: Add man page. * rngd.c: Update --help output, listing defaults. Move 'arguments' local to top of file, call it default_arguments. Fri Mar 23 2001 Philipp Rumpf * rngd.c: fix mixed-up options Fri Mar 23 2001 Philipp Rumpf * rngd.c: add argp support * rngd.c: make random write granularity, poll timeout command line options * rngd.c: optionally daemonize Fri Mar 23 2001 Jeff Garzik * Makefile.am, configure.in, contrib/Makefile.am, autogen.sh, NEWS, ChangeLog, AUTHORS, README, contrib/Makefile.am: Add autoconf/automake support. rng-tools-4/rngd_entsource.c0000664000175000017500000001242212202431225014476 0ustar rtgrtg/* * rngd_entsource.c -- Entropy source and conditioning * * Copyright (C) 2001 Philipp Rumpf * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #define _GNU_SOURCE #ifndef HAVE_CONFIG_H #error Invalid or missing autoconf build environment #endif #include "rng-tools-config.h" #include #include #include #include #include #include #include #include #include #include #include "rngd.h" #include "fips.h" #include "exits.h" #include "rngd_entsource.h" /* The overhead incured when tpm returns the random nos as per TCG spec * it is 14 bytes.*/ #define TPM_GET_RNG_OVERHEAD 14 /* Read data from the entropy source */ int xread(void *buf, size_t size, struct rng *ent_src) { size_t off = 0; ssize_t r; while (size > 0) { do { r = read(ent_src->rng_fd, buf + off, size); } while ((r == -1) && (errno == EINTR)); if (r <= 0) break; off += r; size -= r; } if (size) { message(LOG_DAEMON|LOG_ERR, "read error\n"); return -1; } return 0; } /* tpm rng read call to kernel has 13 bytes of overhead * the logic to process this involves reading to a temporary_buf * and copying the no generated to buf */ int xread_tpm(void *buf, size_t size, struct rng *ent_src) { size_t bytes_read = 0; ssize_t r; int retval; unsigned char *temp_buf = NULL; unsigned char rng_cmd[] = { 0, 193, /* TPM_TAG_RQU_COMMAND */ 0, 0, 0, 14, /* length */ 0, 0, 0, 70, /* TPM_ORD_GetRandom */ 0, 0, 0, 0, /* number of bytes to return */ }; char *offset; ent_src->rng_fd = open(ent_src->rng_name, O_RDWR); if (ent_src->rng_fd == -1) { message(LOG_ERR|LOG_INFO,"Unable to open file: %s",ent_src->rng_name); return -1; } temp_buf = (unsigned char *) malloc(size + TPM_GET_RNG_OVERHEAD); memset(temp_buf, 0, (size+TPM_GET_RNG_OVERHEAD)); if (temp_buf == NULL) { message(LOG_ERR|LOG_INFO,"No memory"); close(ent_src->rng_fd); return -1; } /* 32 bits has been reserved for random byte size */ rng_cmd[13] = (unsigned char)(size & 0xFF); rng_cmd[12] = (unsigned char)((size >> 8) & 0xFF); rng_cmd[11] = (unsigned char)((size >> 16) & 0xFF); rng_cmd[10] = (unsigned char)((size >> 24) & 0xFF); offset = buf; while (bytes_read < size) { r=0; while (r < sizeof(rng_cmd)) { retval = write(ent_src->rng_fd, rng_cmd + r, sizeof(rng_cmd) - r); if (retval < 0) { message(LOG_ERR|LOG_INFO, "Error writing %s\n", ent_src->rng_name); retval = -1; goto error_out; } r += retval; } if (r < sizeof(rng_cmd)) { message(LOG_ERR|LOG_INFO, "Error writing %s\n", ent_src->rng_name); retval = -1; goto error_out; } r = read(ent_src->rng_fd, temp_buf,size); r = (r - TPM_GET_RNG_OVERHEAD); if(r <= 0) { message(LOG_ERR|LOG_INFO, "Error reading from TPM, no entropy gathered"); retval = -1; goto error_out; } bytes_read = bytes_read + r; if (bytes_read > size) { memcpy(offset,temp_buf + TPM_GET_RNG_OVERHEAD, r - (bytes_read - size)); break; } memcpy(offset, temp_buf + TPM_GET_RNG_OVERHEAD, r); offset = offset + r; } retval = 0; error_out: close(ent_src->rng_fd); free(temp_buf); return retval; } /* Initialize entropy source */ static int discard_initial_data(struct rng *ent_src) { /* Trash 32 bits of what is probably stale (non-random) * initial state from the RNG. For Intel's, 8 bits would * be enough, but since AMD's generates 32 bits at a time... * * The kernel drivers should be doing this at device powerup, * but at least up to 2.4.24, it doesn't. */ unsigned char tempbuf[4]; xread(tempbuf, sizeof(tempbuf), ent_src); /* Return 32 bits of bootstrap data */ xread(tempbuf, sizeof(tempbuf), ent_src); return tempbuf[0] | (tempbuf[1] << 8) | (tempbuf[2] << 16) | (tempbuf[3] << 24); } /* * Open entropy source, and initialize it */ int init_entropy_source(struct rng *ent_src) { ent_src->rng_fd = open(ent_src->rng_name, O_RDONLY); if (ent_src->rng_fd == -1) { return 1; } src_list_add(ent_src); /* Bootstrap FIPS tests */ ent_src->fipsctx = malloc(sizeof(fips_ctx_t)); fips_init(ent_src->fipsctx, discard_initial_data(ent_src)); return 0; } /* * Open tpm entropy source, and initialize it */ int init_tpm_entropy_source(struct rng *ent_src) { ent_src->rng_fd = open(ent_src->rng_name, O_RDWR); if (ent_src->rng_fd == -1) { message(LOG_ERR|LOG_INFO,"Unable to open file: %s",ent_src->rng_name); return 1; } src_list_add(ent_src); /* Bootstrap FIPS tests */ ent_src->fipsctx = malloc(sizeof(fips_ctx_t)); fips_init(ent_src->fipsctx, 0); close(ent_src->rng_fd); return 0; } rng-tools-4/NEWS0000664000175000017500000000172712202425744012027 0ustar rtgrtg Version 4 (August 2, 2012): * Add RDRAND instruction support * Add -q and -v options for quiet and verbose output * Add -p option for specifying PID file (text file containing daemon's PID) * Disable entropy source if facing continued failures, but be tolerant of the occasional fault. * Default device is now the preferred /dev/hwrng * Do not use TPM device for RNG access, if /dev/hwrng is present (TPM RNG is exported via the kernel, in newer kernels) Version 3 (July 3, 2010): * add rngtest program * imported into git repository * support TPM chip's hardware RNG (and thus, a framework for supporting multiple entropy sources) * change default hardware RNG device name to "/dev/hw_random" Version 2 (August 24, 2004): * Fixes and cleanups from Debian (Henrique de Moraes Holschuh) Assures rngd works with 2.6 kernels. Version 1.1 (April 6, 2004): * update to recent autoconf/automake * add new rngtest program * various minor cleanups * much better FIPS testing rng-tools-4/rngtest.c0000664000175000017500000002414412202431225013147 0ustar rtgrtg/* * rngtest.c -- Random Number Generator FIPS 140-1/140-2 tests * * This program tests the input stream in stdin for randomness, * using the tests defined by FIPS 140-1/140-2 2001-10-10. * * Copyright (C) 2004 Henrique de Moraes Holschuh * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #define _GNU_SOURCE #ifndef HAVE_CONFIG_H #error Invalid or missing autoconf build environment #endif #include "rng-tools-config.h" #include #include #include #include #include #include #include #include #include #include "fips.h" #include "stats.h" #include "exits.h" #define PROGNAME "rngtest" const char* logprefix = PROGNAME ": "; /* * argp stuff */ const char *argp_program_version = PROGNAME " " VERSION "\n" "Copyright (c) 2004 by Henrique de Moraes Holschuh\n" "This is free software; see the source for copying conditions. There is NO " "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."; const char *argp_program_bug_address = PACKAGE_BUGREPORT; error_t argp_err_exit_status = EXIT_USAGE; static char doc[] = "Check the randomness of data using FIPS 140-2 RNG tests.\n" "\v" "FIPS tests operate on 20000-bit blocks. Data is read from stdin. Statistics " "and messages are sent to stderr.\n\n" "If no errors happen nor any blocks fail the FIPS tests, the program will return " "exit status 0. If any blocks fail the tests, the exit status will be 1.\n"; static struct argp_option options[] = { { "blockcount", 'c', "n", 0, "Exit after processing n blocks (default: 0)" }, { "pipe", 'p', 0, 0, "Enable pipe mode: work silently, and echo to stdout all good blocks" }, { "timedstats", 't', "n", 0, "Dump statistics every n secods (default: 0)" }, { "blockstats", 'b', "n", 0, "Dump statistics every n blocks (default: 0)" }, { 0 }, }; struct arguments { int blockstats; uint64_t timedstats; /* microseconds */ int pipemode; int blockcount; }; static struct arguments default_arguments = { .blockstats = 0, .timedstats = 0, .pipemode = 0, .blockcount = 0, }; static error_t parse_opt (int key, char *arg, struct argp_state *state) { struct arguments *arguments = state->input; switch(key) { case 'c': { int n; if ((sscanf(arg, "%i", &n) == 0) || (n < 0)) argp_usage(state); else arguments->blockcount = n; break; } case 'b': { int n; if ((sscanf(arg, "%i", &n) == 0) || (n < 0)) argp_usage(state); else arguments->blockstats = n; break; } case 't': { int n; if ((sscanf(arg, "%i", &n) == 0) || (n < 0)) argp_usage(state); else arguments->timedstats = 1000000ULL * n; break; } case 'p': arguments->pipemode = 1; break; default: return ARGP_ERR_UNKNOWN; } return 0; } /* * Globals */ /* RNG Buffers */ unsigned char rng_buffer[FIPS_RNG_BUFFER_SIZE]; /* Statistics */ struct { /* simple counters */ uint64_t bad_fips_blocks; /* Blocks reproved by FIPS 140-2 */ uint64_t good_fips_blocks; /* Blocks approved by FIPS 140-2 */ uint64_t fips_failures[N_FIPS_TESTS]; /* Breakdown of block failures per FIPS test */ uint64_t bytes_received; /* Bytes read from input */ uint64_t bytes_sent; /* Bytes sent to output */ /* performance timers */ struct rng_stat source_blockfill; /* Block-receive time */ struct rng_stat fips_blockfill; /* FIPS run time */ struct rng_stat sink_blockfill; /* Block-send time */ struct timeval progstart; /* Program start time */ } rng_stats; /* Logic and contexts */ static fips_ctx_t fipsctx; /* Context for the FIPS tests */ static int exitstatus = EXIT_SUCCESS; /* Exit status */ /* Command line arguments and processing */ struct arguments *arguments = &default_arguments; static struct argp argp = { options, parse_opt, NULL, doc }; /* signals */ static volatile int gotsigterm = 0; /* Received SIGTERM/SIGINT */ /* * Signal handling */ static void sigterm_handler(int sig) { gotsigterm = sig; } static void init_sighandlers(void) { struct sigaction action; sigemptyset(&action.sa_mask); action.sa_flags = 0; action.sa_handler = sigterm_handler; /* Handle SIGTERM and SIGINT the same way */ if (sigaction(SIGTERM, &action, NULL) < 0) { fprintf(stderr, "unable to install signal handler for SIGTERM: %s", strerror(errno)); exit(EXIT_OSERR); } if (sigaction(SIGINT, &action, NULL) < 0) { fprintf(stderr, "unable to install signal handler for SIGINT: %s", strerror(errno)); exit(EXIT_OSERR); } } static int xread(void *buf, size_t size) { size_t off = 0; ssize_t r; while (size) { r = read(0, buf + off, size); if (r < 0) { if (gotsigterm) return -1; if ((errno == EAGAIN) || (errno == EINTR)) continue; break; } else if (!r) { if (!arguments->pipemode) fprintf(stderr, "%sentropy source drained\n", logprefix); return -1; } off += r; size -= r; rng_stats.bytes_received += r; } if (size) { fprintf(stderr, "%serror reading input: %s\n", logprefix, strerror(errno)); exitstatus = EXIT_IOERR; return -1; } return 0; } static int xwrite(void *buf, size_t size) { size_t off = 0; ssize_t r; while (size) { r = write(1, buf + off, size); if (r < 0) { if (gotsigterm) return -1; if ((errno == EAGAIN) || (errno == EINTR)) continue; break; } else if (!r) { fprintf(stderr, "%swrite channel stuck\n", logprefix); exitstatus = EXIT_IOERR; return -1; } off += r; size -= r; rng_stats.bytes_sent += r; } if (size) { fprintf(stderr, "%serror writing to output: %s\n", logprefix, strerror(errno)); exitstatus = EXIT_IOERR; return -1; } return 0; } static void init_rng_stats(void) { memset(&rng_stats, 0, sizeof(rng_stats)); gettimeofday(&rng_stats.progstart, 0); set_stat_prefix(logprefix); } static void dump_rng_stats(void) { int j; char buf[256]; struct timeval now; fprintf(stderr, "%s\n", dump_stat_counter(buf, sizeof(buf), "bits received from input", rng_stats.bytes_received * 8)); if (arguments->pipemode) fprintf(stderr, "%s\n", dump_stat_counter(buf, sizeof(buf), "bits sent to output", rng_stats.bytes_sent * 8)); fprintf(stderr, "%s\n", dump_stat_counter(buf, sizeof(buf), "FIPS 140-2 successes", rng_stats.good_fips_blocks)); fprintf(stderr, "%s\n", dump_stat_counter(buf, sizeof(buf), "FIPS 140-2 failures", rng_stats.bad_fips_blocks)); for (j = 0; j < N_FIPS_TESTS; j++) fprintf(stderr, "%s\n", dump_stat_counter(buf, sizeof(buf), fips_test_names[j], rng_stats.fips_failures[j])); fprintf(stderr, "%s\n", dump_stat_bw(buf, sizeof(buf), "input channel speed", "bits", &rng_stats.source_blockfill, FIPS_RNG_BUFFER_SIZE*8)); fprintf(stderr, "%s\n", dump_stat_bw(buf, sizeof(buf), "FIPS tests speed", "bits", &rng_stats.fips_blockfill, FIPS_RNG_BUFFER_SIZE*8)); if (arguments->pipemode) fprintf(stderr, "%s\n", dump_stat_bw(buf, sizeof(buf), "output channel speed", "bits", &rng_stats.sink_blockfill, FIPS_RNG_BUFFER_SIZE*8)); gettimeofday(&now, 0); fprintf(stderr, "%sProgram run time: %llu microseconds\n", logprefix, (unsigned long long) elapsed_time(&rng_stats.progstart, &now)); } /* Return 32 bits of bootstrap data */ static int discard_initial_data(void) { unsigned char tempbuf[4]; /* Do full startup discards when in pipe mode */ if (arguments->pipemode) if (xread(tempbuf, sizeof tempbuf)) exit(EXIT_FAIL); /* Bootstrap data for FIPS tests */ if (xread(tempbuf, sizeof tempbuf)) exit(EXIT_FAIL); return tempbuf[0] | (tempbuf[1] << 8) | (tempbuf[2] << 16) | (tempbuf[3] << 24); } static void do_rng_fips_test_loop( void ) { int j; int fips_result; struct timeval start, stop, statdump, now; int statruns, runs; runs = statruns = 0; gettimeofday(&statdump, 0); while (!gotsigterm) { gettimeofday(&start, 0); if (xread(rng_buffer, sizeof(rng_buffer))) return; gettimeofday(&stop, 0); update_usectimer_stat(&rng_stats.source_blockfill, &start, &stop); gettimeofday(&start, 0); fips_result = fips_run_rng_test(&fipsctx, &rng_buffer); gettimeofday (&stop, 0); update_usectimer_stat(&rng_stats.fips_blockfill, &start, &stop); if (fips_result) { rng_stats.bad_fips_blocks++; for (j = 0; j < N_FIPS_TESTS; j++) if (fips_result & fips_test_mask[j]) rng_stats.fips_failures[j]++; } else { rng_stats.good_fips_blocks++; if (arguments->pipemode) { gettimeofday(&start, 0); if (xwrite(rng_buffer, sizeof(rng_buffer))) return; gettimeofday (&stop, 0); update_usectimer_stat( &rng_stats.sink_blockfill, &start, &stop); } } if (arguments->blockcount && (++runs >= arguments->blockcount)) break; gettimeofday(&now, 0); if ((arguments->blockstats && (++statruns >= arguments->blockstats)) || (arguments->timedstats && (elapsed_time(&statdump, &now) > arguments->timedstats))) { dump_rng_stats(); gettimeofday(&statdump, 0); statruns = 0; } } } int main(int argc, char **argv) { argp_parse(&argp, argc, argv, 0, 0, arguments); if (!arguments->pipemode) fprintf(stderr, "%s\n\n", argp_program_version); init_sighandlers(); /* Init data structures */ init_rng_stats(); if (!arguments->pipemode) fprintf(stderr, "%sstarting FIPS tests...\n", logprefix); /* Bootstrap FIPS tests */ fips_init(&fipsctx, discard_initial_data()); do_rng_fips_test_loop(); dump_rng_stats(); if ((exitstatus == EXIT_SUCCESS) && (rng_stats.bad_fips_blocks || !rng_stats.good_fips_blocks)) { exitstatus = EXIT_FAIL; } exit(exitstatus); } rng-tools-4/stats.c0000664000175000017500000000756012202431225012622 0ustar rtgrtg/* * stats.c -- Statistics helpers * * Copyright (C) 2004 Henrique de Moraes Holschuh * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #define _GNU_SOURCE #ifndef HAVE_CONFIG_H #error Invalid or missing autoconf build environment #endif #include "rng-tools-config.h" #include #include #include #include #include #include #include "fips.h" #include "stats.h" static char stat_prefix[20] = ""; void set_stat_prefix(const char* prefix) { stat_prefix[sizeof(stat_prefix)-1] = 0; strncpy(stat_prefix, prefix, sizeof(stat_prefix)-1); } static void scale_mult_unit(char *unit, int unitsize, const char *baseunit, double *value_min, double *value_avg, double *value_max) { int mult = 0; char multchar[] = "KMGTPE"; while ((*value_min >= 1024.0) && (*value_avg >= 1024.0) && (*value_max >= 1024.0) && (mult < sizeof(multchar))) { mult++; *value_min = *value_min / 1024.0; *value_max = *value_max / 1024.0; *value_avg = *value_avg / 1024.0; } unit[unitsize-1] = 0; if (mult) snprintf(unit, unitsize, "%ci%s", multchar[mult-1], baseunit); else strncpy(unit, baseunit, unitsize); } /* Computes elapsed time in microseconds */ uint64_t elapsed_time(struct timeval *start, struct timeval *stop) { uint64_t diff; if (stop->tv_sec < start->tv_sec) return 0; diff = (stop->tv_sec - start->tv_sec) * 1000000ULL; if (stop->tv_usec > start->tv_usec) { diff += stop->tv_usec - start->tv_usec; } else { diff -= start->tv_usec - stop->tv_usec; } return diff; } /* Updates min-max stat */ void update_stat(struct rng_stat *stat, uint64_t value) { uint64_t overflow = stat->num_samples; if ((stat->min == 0 ) || (value < stat->min)) stat->min = value; if (value > stat->max) stat->max = value; if (++stat->num_samples > overflow) { stat->sum += value; } else { stat->sum = value; stat->num_samples = 1; } } char *dump_stat_counter(char *buf, int size, const char *msg, uint64_t value) { buf[size-1] = 0; snprintf(buf, size-1, "%s%s: %llu", stat_prefix, msg, (unsigned long long) value); return buf; } char *dump_stat_stat(char *buf, int size, const char *msg, const char *unit, struct rng_stat *stat) { double avg = 0.0; if (stat->num_samples > 0) avg = (double)stat->sum / stat->num_samples; buf[size-1] = 0; snprintf(buf, size-1, "%s%s: (min=%llu; avg=%.3f; max=%llu)%s", stat_prefix, msg, (unsigned long long) stat->min, avg, (unsigned long long) stat->max, unit); return buf; } char *dump_stat_bw(char *buf, int size, const char *msg, const char *unit, struct rng_stat *stat, uint64_t blocksize) { char unitscaled[20]; double bw_avg = 0.0, bw_min = 0.0, bw_max = 0.0; if (stat->max > 0) bw_min = (1000000.0 * blocksize) / stat->max; if (stat->min > 0) bw_max = (1000000.0 * blocksize) / stat->min; if (stat->num_samples > 0) bw_avg = (1000000.0 * blocksize * stat->num_samples) / stat->sum; scale_mult_unit(unitscaled, sizeof(unitscaled), unit, &bw_min, &bw_avg, &bw_max); buf[size-1] = 0; snprintf(buf, size-1, "%s%s: (min=%.3f; avg=%.3f; max=%.3f)%s/s", stat_prefix, msg, bw_min, bw_avg, bw_max, unitscaled); return buf; } rng-tools-4/contrib/0000775000175000017500000000000012202425744012761 5ustar rtgrtgrng-tools-4/contrib/Makefile.am0000664000175000017500000000003212202425744015010 0ustar rtgrtg EXTRA_DIST = randstat.c rng-tools-4/contrib/rngtest.c0000664000175000017500000000722312202425744014617 0ustar rtgrtg/* These are the Random Number Generator tests suggested by the FIPS 140-1 spec section 4.11.1 (http://csrc.nist.gov/fips/fips1401.htm) The Monobit, Poker, Runs, and Long Runs tests are implemented below. */ #define RNG_DEVICE "/dev/hwrandom" #define RNG_LOOPS 25 #include FILE *dev; char read_rng_byte() { char random; fscanf(dev,"%c",&random); return random; } int do_test() { unsigned char rbyte = 0; int poker[16],runs[12],i,j; double pokertest; int longrun = 0; int current = 0; int rlength = 0; int ones = 0; for(i=0; i<16; i++) { poker[i] = 0; } for(i=0; i<12; i++) { runs[i] = 0; } rlength = 999; ones = 0; for(i=0; i<2500; i++) { rbyte = read_rng_byte(); // printf("%d: %x\n",i,rbyte); ones += rbyte & 1; ones += (rbyte & 2)>>1; ones += (rbyte & 4)>>2; ones += (rbyte & 8)>>3; ones += (rbyte & 16)>>4; ones += (rbyte & 32)>>5; ones += (rbyte & 64)>>6; ones += (rbyte & 128)>>7; poker[rbyte>>4] += 1; poker[rbyte & 15] += 1; /* Trick to make sure current != the first bit so we don't screw up the first runlength */ if(rlength == 999) { current = !((rbyte & 128)>>7); rlength = 1; } for(j=7; j>=0; j--) { // printf("%d %d %d\n",rlength,current,((rbyte & 1<>j) ); if(((rbyte & 1<>j) == current) { rlength++; } else { /* If runlength is 1-6 count it in correct bucket. 0's go in runs[0-5] 1's go in runs[6-11] hence the 6*current below */ if(rlength < 6) { runs[rlength - 1 + (6*current)]++; } if(rlength >= 6) { runs[5 + (6*current)]++; } /* Check if we just failed longrun test */ if(rlength > longrun) { longrun = rlength; } rlength=1; /* flip the current run type */ current = (rbyte & 1<>j; } } } /* add in the last (possibly incomplete) run */ if(rlength <= 6) { runs[rlength - 1 + (6*current)]++; } if(rlength > longrun) { longrun = rlength; } /* To poker test */ pokertest = 0; for(i=0; i<16; i++) { // printf("P%d: %d\n",i,poker[i]); pokertest += (double)(poker[i] * poker[i]); } pokertest = (16.0/5000.0) * pokertest - 5000.0; /* Data is all gathered, do the tests */ printf("Ones: %d\nPokertest: %f\nRuns: %d %d %d %d %d %d\n %d %d %d %d %d %d\nLong Run: %d\n\n",ones,(float)pokertest,runs[0],runs[1],runs[2],runs[3],runs[4],runs[5],runs[6],runs[7],runs[8],runs[9],runs[10],runs[11],longrun); if(! ((ones < 10346) && (ones > 9654)) ){ printf(" RNG failed Monobit test.\n"); return 1; } if(! ((pokertest < 57.4) && (pokertest > 1.03)) ){ printf(" RNG failed Poker test.\n"); return 1; } if(! ((runs[0] >= 2267) && (runs[0] <= 2733) && (runs[1] >= 1079) && (runs[1] <= 1421) && (runs[2] >= 502) && (runs[2] <= 748) && (runs[3] >= 223) && (runs[3] <= 402) && (runs[4] >= 90) && (runs[4] <= 223) && (runs[5] >= 90) && (runs[5] <= 223) && (runs[6] >= 2267) && (runs[6] <= 2733) && (runs[7] >= 1079) && (runs[7] <= 1421) && (runs[8] >= 502) && (runs[8] <= 748) && (runs[9] >= 223) && (runs[9] <= 402) && (runs[10] >= 90) && (runs[10] <= 223) && (runs[11] >= 90) && (runs[11] <= 223)) ) { printf(" RNG failed Runs test.\n"); return 1; } if(longrun >= 34) { printf(" RNG failed LongRun test.\n"); return 1; } return 0; } int main(int argv,char **argc) { unsigned char random; int i=0; if(! (dev = fopen(RNG_DEVICE,"r"))) { printf("Open of "RNG_DEVICE" failed\n"); exit(1); } for(i=0; i #include #include #include #include #include #include #include int main(int argc, char **argv) { int random_fd; int ent_count; random_fd = open("/dev/random", O_RDONLY); if (random_fd < 0) return 1; if (ioctl(random_fd, RNDGETENTCNT, &ent_count) != 0) return 1; printf("%d\n", ent_count); return 0; }