OpenSSL 1.1.1-pre2
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
LIBS=../../libcrypto
|
||||
SOURCE[../../libcrypto]=\
|
||||
md_rand.c randfile.c rand_lib.c rand_err.c rand_egd.c \
|
||||
rand_win.c rand_unix.c rand_vms.c
|
||||
randfile.c rand_lib.c rand_err.c rand_egd.c \
|
||||
rand_win.c rand_unix.c rand_vms.c drbg_lib.c drbg_ctr.c
|
||||
@@ -0,0 +1,371 @@
|
||||
/*
|
||||
* Copyright 2011-2018 The OpenSSL Project Authors. All Rights Reserved.
|
||||
*
|
||||
* Licensed under the OpenSSL license (the "License"). You may not use
|
||||
* this file except in compliance with the License. You can obtain a copy
|
||||
* in the file LICENSE in the source distribution or at
|
||||
* https://www.openssl.org/source/license.html
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <openssl/crypto.h>
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/rand.h>
|
||||
#include "rand_lcl.h"
|
||||
#include "internal/thread_once.h"
|
||||
|
||||
/*
|
||||
* Implementation of NIST SP 800-90A CTR DRBG.
|
||||
*/
|
||||
|
||||
static void inc_128(RAND_DRBG_CTR *ctr)
|
||||
{
|
||||
int i;
|
||||
unsigned char c;
|
||||
unsigned char *p = &ctr->V[15];
|
||||
|
||||
for (i = 0; i < 16; i++, p--) {
|
||||
c = *p;
|
||||
c++;
|
||||
*p = c;
|
||||
if (c != 0) {
|
||||
/* If we didn't wrap around, we're done. */
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void ctr_XOR(RAND_DRBG_CTR *ctr, const unsigned char *in, size_t inlen)
|
||||
{
|
||||
size_t i, n;
|
||||
|
||||
if (in == NULL || inlen == 0)
|
||||
return;
|
||||
|
||||
/*
|
||||
* Any zero padding will have no effect on the result as we
|
||||
* are XORing. So just process however much input we have.
|
||||
*/
|
||||
n = inlen < ctr->keylen ? inlen : ctr->keylen;
|
||||
for (i = 0; i < n; i++)
|
||||
ctr->K[i] ^= in[i];
|
||||
if (inlen <= ctr->keylen)
|
||||
return;
|
||||
|
||||
n = inlen - ctr->keylen;
|
||||
if (n > 16) {
|
||||
/* Should never happen */
|
||||
n = 16;
|
||||
}
|
||||
for (i = 0; i < n; i++)
|
||||
ctr->V[i] ^= in[i + ctr->keylen];
|
||||
}
|
||||
|
||||
/*
|
||||
* Process a complete block using BCC algorithm of SP 800-90A 10.3.3
|
||||
*/
|
||||
static void ctr_BCC_block(RAND_DRBG_CTR *ctr, unsigned char *out,
|
||||
const unsigned char *in)
|
||||
{
|
||||
int i;
|
||||
|
||||
for (i = 0; i < 16; i++)
|
||||
out[i] ^= in[i];
|
||||
AES_encrypt(out, out, &ctr->df_ks);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Handle several BCC operations for as much data as we need for K and X
|
||||
*/
|
||||
static void ctr_BCC_blocks(RAND_DRBG_CTR *ctr, const unsigned char *in)
|
||||
{
|
||||
ctr_BCC_block(ctr, ctr->KX, in);
|
||||
ctr_BCC_block(ctr, ctr->KX + 16, in);
|
||||
if (ctr->keylen != 16)
|
||||
ctr_BCC_block(ctr, ctr->KX + 32, in);
|
||||
}
|
||||
|
||||
/*
|
||||
* Initialise BCC blocks: these have the value 0,1,2 in leftmost positions:
|
||||
* see 10.3.1 stage 7.
|
||||
*/
|
||||
static void ctr_BCC_init(RAND_DRBG_CTR *ctr)
|
||||
{
|
||||
memset(ctr->KX, 0, 48);
|
||||
memset(ctr->bltmp, 0, 16);
|
||||
ctr_BCC_block(ctr, ctr->KX, ctr->bltmp);
|
||||
ctr->bltmp[3] = 1;
|
||||
ctr_BCC_block(ctr, ctr->KX + 16, ctr->bltmp);
|
||||
if (ctr->keylen != 16) {
|
||||
ctr->bltmp[3] = 2;
|
||||
ctr_BCC_block(ctr, ctr->KX + 32, ctr->bltmp);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Process several blocks into BCC algorithm, some possibly partial
|
||||
*/
|
||||
static void ctr_BCC_update(RAND_DRBG_CTR *ctr,
|
||||
const unsigned char *in, size_t inlen)
|
||||
{
|
||||
if (in == NULL || inlen == 0)
|
||||
return;
|
||||
|
||||
/* If we have partial block handle it first */
|
||||
if (ctr->bltmp_pos) {
|
||||
size_t left = 16 - ctr->bltmp_pos;
|
||||
|
||||
/* If we now have a complete block process it */
|
||||
if (inlen >= left) {
|
||||
memcpy(ctr->bltmp + ctr->bltmp_pos, in, left);
|
||||
ctr_BCC_blocks(ctr, ctr->bltmp);
|
||||
ctr->bltmp_pos = 0;
|
||||
inlen -= left;
|
||||
in += left;
|
||||
}
|
||||
}
|
||||
|
||||
/* Process zero or more complete blocks */
|
||||
for (; inlen >= 16; in += 16, inlen -= 16) {
|
||||
ctr_BCC_blocks(ctr, in);
|
||||
}
|
||||
|
||||
/* Copy any remaining partial block to the temporary buffer */
|
||||
if (inlen > 0) {
|
||||
memcpy(ctr->bltmp + ctr->bltmp_pos, in, inlen);
|
||||
ctr->bltmp_pos += inlen;
|
||||
}
|
||||
}
|
||||
|
||||
static void ctr_BCC_final(RAND_DRBG_CTR *ctr)
|
||||
{
|
||||
if (ctr->bltmp_pos) {
|
||||
memset(ctr->bltmp + ctr->bltmp_pos, 0, 16 - ctr->bltmp_pos);
|
||||
ctr_BCC_blocks(ctr, ctr->bltmp);
|
||||
}
|
||||
}
|
||||
|
||||
static void ctr_df(RAND_DRBG_CTR *ctr,
|
||||
const unsigned char *in1, size_t in1len,
|
||||
const unsigned char *in2, size_t in2len,
|
||||
const unsigned char *in3, size_t in3len)
|
||||
{
|
||||
static unsigned char c80 = 0x80;
|
||||
size_t inlen;
|
||||
unsigned char *p = ctr->bltmp;
|
||||
|
||||
ctr_BCC_init(ctr);
|
||||
if (in1 == NULL)
|
||||
in1len = 0;
|
||||
if (in2 == NULL)
|
||||
in2len = 0;
|
||||
if (in3 == NULL)
|
||||
in3len = 0;
|
||||
inlen = in1len + in2len + in3len;
|
||||
/* Initialise L||N in temporary block */
|
||||
*p++ = (inlen >> 24) & 0xff;
|
||||
*p++ = (inlen >> 16) & 0xff;
|
||||
*p++ = (inlen >> 8) & 0xff;
|
||||
*p++ = inlen & 0xff;
|
||||
|
||||
/* NB keylen is at most 32 bytes */
|
||||
*p++ = 0;
|
||||
*p++ = 0;
|
||||
*p++ = 0;
|
||||
*p = (unsigned char)((ctr->keylen + 16) & 0xff);
|
||||
ctr->bltmp_pos = 8;
|
||||
ctr_BCC_update(ctr, in1, in1len);
|
||||
ctr_BCC_update(ctr, in2, in2len);
|
||||
ctr_BCC_update(ctr, in3, in3len);
|
||||
ctr_BCC_update(ctr, &c80, 1);
|
||||
ctr_BCC_final(ctr);
|
||||
/* Set up key K */
|
||||
AES_set_encrypt_key(ctr->KX, ctr->keylen * 8, &ctr->df_kxks);
|
||||
/* X follows key K */
|
||||
AES_encrypt(ctr->KX + ctr->keylen, ctr->KX, &ctr->df_kxks);
|
||||
AES_encrypt(ctr->KX, ctr->KX + 16, &ctr->df_kxks);
|
||||
if (ctr->keylen != 16)
|
||||
AES_encrypt(ctr->KX + 16, ctr->KX + 32, &ctr->df_kxks);
|
||||
}
|
||||
|
||||
/*
|
||||
* NB the no-df Update in SP800-90A specifies a constant input length
|
||||
* of seedlen, however other uses of this algorithm pad the input with
|
||||
* zeroes if necessary and have up to two parameters XORed together,
|
||||
* so we handle both cases in this function instead.
|
||||
*/
|
||||
static void ctr_update(RAND_DRBG *drbg,
|
||||
const unsigned char *in1, size_t in1len,
|
||||
const unsigned char *in2, size_t in2len,
|
||||
const unsigned char *nonce, size_t noncelen)
|
||||
{
|
||||
RAND_DRBG_CTR *ctr = &drbg->data.ctr;
|
||||
|
||||
/* ks is already setup for correct key */
|
||||
inc_128(ctr);
|
||||
AES_encrypt(ctr->V, ctr->K, &ctr->ks);
|
||||
|
||||
/* If keylen longer than 128 bits need extra encrypt */
|
||||
if (ctr->keylen != 16) {
|
||||
inc_128(ctr);
|
||||
AES_encrypt(ctr->V, ctr->K + 16, &ctr->ks);
|
||||
}
|
||||
inc_128(ctr);
|
||||
AES_encrypt(ctr->V, ctr->V, &ctr->ks);
|
||||
|
||||
/* If 192 bit key part of V is on end of K */
|
||||
if (ctr->keylen == 24) {
|
||||
memcpy(ctr->V + 8, ctr->V, 8);
|
||||
memcpy(ctr->V, ctr->K + 24, 8);
|
||||
}
|
||||
|
||||
if ((drbg->flags & RAND_DRBG_FLAG_CTR_NO_DF) == 0) {
|
||||
/* If no input reuse existing derived value */
|
||||
if (in1 != NULL || nonce != NULL || in2 != NULL)
|
||||
ctr_df(ctr, in1, in1len, nonce, noncelen, in2, in2len);
|
||||
/* If this a reuse input in1len != 0 */
|
||||
if (in1len)
|
||||
ctr_XOR(ctr, ctr->KX, drbg->seedlen);
|
||||
} else {
|
||||
ctr_XOR(ctr, in1, in1len);
|
||||
ctr_XOR(ctr, in2, in2len);
|
||||
}
|
||||
|
||||
AES_set_encrypt_key(ctr->K, drbg->strength, &ctr->ks);
|
||||
}
|
||||
|
||||
static int drbg_ctr_instantiate(RAND_DRBG *drbg,
|
||||
const unsigned char *entropy, size_t entropylen,
|
||||
const unsigned char *nonce, size_t noncelen,
|
||||
const unsigned char *pers, size_t perslen)
|
||||
{
|
||||
RAND_DRBG_CTR *ctr = &drbg->data.ctr;
|
||||
|
||||
if (entropy == NULL)
|
||||
return 0;
|
||||
|
||||
memset(ctr->K, 0, sizeof(ctr->K));
|
||||
memset(ctr->V, 0, sizeof(ctr->V));
|
||||
AES_set_encrypt_key(ctr->K, drbg->strength, &ctr->ks);
|
||||
ctr_update(drbg, entropy, entropylen, pers, perslen, nonce, noncelen);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int drbg_ctr_reseed(RAND_DRBG *drbg,
|
||||
const unsigned char *entropy, size_t entropylen,
|
||||
const unsigned char *adin, size_t adinlen)
|
||||
{
|
||||
if (entropy == NULL)
|
||||
return 0;
|
||||
ctr_update(drbg, entropy, entropylen, adin, adinlen, NULL, 0);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int drbg_ctr_generate(RAND_DRBG *drbg,
|
||||
unsigned char *out, size_t outlen,
|
||||
const unsigned char *adin, size_t adinlen)
|
||||
{
|
||||
RAND_DRBG_CTR *ctr = &drbg->data.ctr;
|
||||
|
||||
if (adin != NULL && adinlen != 0) {
|
||||
ctr_update(drbg, adin, adinlen, NULL, 0, NULL, 0);
|
||||
/* This means we reuse derived value */
|
||||
if ((drbg->flags & RAND_DRBG_FLAG_CTR_NO_DF) == 0) {
|
||||
adin = NULL;
|
||||
adinlen = 1;
|
||||
}
|
||||
} else {
|
||||
adinlen = 0;
|
||||
}
|
||||
|
||||
for ( ; ; ) {
|
||||
inc_128(ctr);
|
||||
if (outlen < 16) {
|
||||
/* Use K as temp space as it will be updated */
|
||||
AES_encrypt(ctr->V, ctr->K, &ctr->ks);
|
||||
memcpy(out, ctr->K, outlen);
|
||||
break;
|
||||
}
|
||||
AES_encrypt(ctr->V, out, &ctr->ks);
|
||||
out += 16;
|
||||
outlen -= 16;
|
||||
if (outlen == 0)
|
||||
break;
|
||||
}
|
||||
|
||||
ctr_update(drbg, adin, adinlen, NULL, 0, NULL, 0);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int drbg_ctr_uninstantiate(RAND_DRBG *drbg)
|
||||
{
|
||||
OPENSSL_cleanse(&drbg->data.ctr, sizeof(drbg->data.ctr));
|
||||
return 1;
|
||||
}
|
||||
|
||||
static RAND_DRBG_METHOD drbg_ctr_meth = {
|
||||
drbg_ctr_instantiate,
|
||||
drbg_ctr_reseed,
|
||||
drbg_ctr_generate,
|
||||
drbg_ctr_uninstantiate
|
||||
};
|
||||
|
||||
int drbg_ctr_init(RAND_DRBG *drbg)
|
||||
{
|
||||
RAND_DRBG_CTR *ctr = &drbg->data.ctr;
|
||||
size_t keylen;
|
||||
|
||||
switch (drbg->nid) {
|
||||
default:
|
||||
/* This can't happen, but silence the compiler warning. */
|
||||
return 0;
|
||||
case NID_aes_128_ctr:
|
||||
keylen = 16;
|
||||
break;
|
||||
case NID_aes_192_ctr:
|
||||
keylen = 24;
|
||||
break;
|
||||
case NID_aes_256_ctr:
|
||||
keylen = 32;
|
||||
break;
|
||||
}
|
||||
|
||||
drbg->meth = &drbg_ctr_meth;
|
||||
|
||||
ctr->keylen = keylen;
|
||||
drbg->strength = keylen * 8;
|
||||
drbg->seedlen = keylen + 16;
|
||||
|
||||
if ((drbg->flags & RAND_DRBG_FLAG_CTR_NO_DF) == 0) {
|
||||
/* df initialisation */
|
||||
static unsigned char df_key[32] = {
|
||||
0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,
|
||||
0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,
|
||||
0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,
|
||||
0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f
|
||||
};
|
||||
/* Set key schedule for df_key */
|
||||
AES_set_encrypt_key(df_key, drbg->strength, &ctr->df_ks);
|
||||
|
||||
drbg->min_entropylen = ctr->keylen;
|
||||
drbg->max_entropylen = DRBG_MINMAX_FACTOR * drbg->min_entropylen;
|
||||
drbg->min_noncelen = drbg->min_entropylen / 2;
|
||||
drbg->max_noncelen = DRBG_MINMAX_FACTOR * drbg->min_noncelen;
|
||||
drbg->max_perslen = DRBG_MAX_LENGTH;
|
||||
drbg->max_adinlen = DRBG_MAX_LENGTH;
|
||||
} else {
|
||||
drbg->min_entropylen = drbg->seedlen;
|
||||
drbg->max_entropylen = drbg->seedlen;
|
||||
/* Nonce not used */
|
||||
drbg->min_noncelen = 0;
|
||||
drbg->max_noncelen = 0;
|
||||
drbg->max_perslen = drbg->seedlen;
|
||||
drbg->max_adinlen = drbg->seedlen;
|
||||
}
|
||||
|
||||
drbg->max_request = 1 << 16;
|
||||
drbg->reseed_interval = MAX_RESEED_INTERVAL;
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,980 @@
|
||||
/*
|
||||
* Copyright 2011-2018 The OpenSSL Project Authors. All Rights Reserved.
|
||||
*
|
||||
* Licensed under the OpenSSL license (the "License"). You may not use
|
||||
* this file except in compliance with the License. You can obtain a copy
|
||||
* in the file LICENSE in the source distribution or at
|
||||
* https://www.openssl.org/source/license.html
|
||||
*/
|
||||
|
||||
#include <string.h>
|
||||
#include <openssl/crypto.h>
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/rand.h>
|
||||
#include "rand_lcl.h"
|
||||
#include "internal/thread_once.h"
|
||||
#include "internal/rand_int.h"
|
||||
|
||||
/*
|
||||
* Support framework for NIST SP 800-90A DRBG, AES-CTR mode.
|
||||
* The RAND_DRBG is OpenSSL's pointer to an instance of the DRBG.
|
||||
*
|
||||
* The OpenSSL model is to have new and free functions, and that new
|
||||
* does all initialization. That is not the NIST model, which has
|
||||
* instantiation and un-instantiate, and re-use within a new/free
|
||||
* lifecycle. (No doubt this comes from the desire to support hardware
|
||||
* DRBG, where allocation of resources on something like an HSM is
|
||||
* a much bigger deal than just re-setting an allocated resource.)
|
||||
*/
|
||||
|
||||
/*
|
||||
* THE THREE SHARED DRBGs
|
||||
*
|
||||
* There are three shared DRBGs (master, public and private), which are
|
||||
* accessed concurrently by all threads.
|
||||
*
|
||||
* THE MASTER DRBG
|
||||
*
|
||||
* Not used directly by the application, only for reseeding the two other
|
||||
* DRBGs. It reseeds itself by pulling either randomness from os entropy
|
||||
* sources or by consuming randomnes which was added by RAND_add()
|
||||
*/
|
||||
static RAND_DRBG *drbg_master;
|
||||
/*
|
||||
* THE PUBLIC DRBG
|
||||
*
|
||||
* Used by default for generating random bytes using RAND_bytes().
|
||||
*/
|
||||
static RAND_DRBG *drbg_public;
|
||||
/*
|
||||
* THE PRIVATE DRBG
|
||||
*
|
||||
* Used by default for generating private keys using RAND_priv_bytes()
|
||||
*/
|
||||
static RAND_DRBG *drbg_private;
|
||||
/*+
|
||||
* DRBG HIERARCHY
|
||||
*
|
||||
* In addition there are DRBGs, which are not shared, but used only by a
|
||||
* single thread at every time, for example the DRBGs which are owned by
|
||||
* an SSL context. All DRBGs are organized in a hierarchical fashion
|
||||
* with the <master> DRBG as root.
|
||||
*
|
||||
* This gives the following overall picture:
|
||||
*
|
||||
* <os entropy sources>
|
||||
* |
|
||||
* RAND_add() ==> <master> \
|
||||
* / \ | shared DRBGs (with locking)
|
||||
* <public> <private> /
|
||||
* |
|
||||
* <ssl> owned by an SSL context
|
||||
*
|
||||
* AUTOMATIC RESEEDING
|
||||
*
|
||||
* Before satisfying a generate request, a DRBG reseeds itself automatically,
|
||||
* if one of the following two conditions holds:
|
||||
*
|
||||
* - the number of generate requests since the last reseeding exceeds a
|
||||
* certain threshold, the so called |reseed_interval|. This behaviour
|
||||
* can be disabled by setting the |reseed_interval| to 0.
|
||||
*
|
||||
* - the time elapsed since the last reseeding exceeds a certain time
|
||||
* interval, the so called |reseed_time_interval|. This behaviour
|
||||
* can be disabled by setting the |reseed_time_interval| to 0.
|
||||
*
|
||||
* MANUAL RESEEDING
|
||||
*
|
||||
* For the three shared DRBGs (and only for these) there is another way to
|
||||
* reseed them manually by calling RAND_seed() (or RAND_add() with a positive
|
||||
* |randomness| argument). This will immediately reseed the <master> DRBG.
|
||||
* The <public> and <private> DRBG will detect this on their next generate
|
||||
* call and reseed, pulling randomness from <master>.
|
||||
*
|
||||
* LOCKING
|
||||
*
|
||||
* The three shared DRBGs are intended to be used concurrently, so they
|
||||
* support locking. The RAND methods take the locks automatically, so using
|
||||
* the RAND api (in particular RAND_bytes() and RAND_priv_bytes()) is
|
||||
* thread-safe. Note however that accessing the shared DRBGs directly via
|
||||
* the RAND_DRBG interface is *not* thread-safe.
|
||||
*
|
||||
* All other DRBG instances don't support locking, because they are
|
||||
* intendended to be used by a single thread. Instead of accessing a single
|
||||
* DRBG instance concurrently from different threads, it is recommended to
|
||||
* instantiate a separate DRBG instance per thread. Using the same shared
|
||||
* DRBG (preferrably the public DRBG) as parent of DRBG instances on
|
||||
* different threads is safe.
|
||||
*/
|
||||
|
||||
|
||||
/* NIST SP 800-90A DRBG recommends the use of a personalization string. */
|
||||
static const char ossl_pers_string[] = "OpenSSL NIST SP 800-90A DRBG";
|
||||
|
||||
static CRYPTO_ONCE rand_drbg_init = CRYPTO_ONCE_STATIC_INIT;
|
||||
|
||||
static RAND_DRBG *drbg_setup(RAND_DRBG *parent);
|
||||
|
||||
static RAND_DRBG *rand_drbg_new(int secure,
|
||||
int type,
|
||||
unsigned int flags,
|
||||
RAND_DRBG *parent);
|
||||
|
||||
/*
|
||||
* Set/initialize |drbg| to be of type |nid|, with optional |flags|.
|
||||
*
|
||||
* Returns 1 on success, 0 on failure.
|
||||
*/
|
||||
int RAND_DRBG_set(RAND_DRBG *drbg, int nid, unsigned int flags)
|
||||
{
|
||||
int ret = 1;
|
||||
|
||||
drbg->state = DRBG_UNINITIALISED;
|
||||
drbg->flags = flags;
|
||||
drbg->nid = nid;
|
||||
|
||||
switch (nid) {
|
||||
default:
|
||||
RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
|
||||
return 0;
|
||||
case 0:
|
||||
/* Uninitialized; that's okay. */
|
||||
return 1;
|
||||
case NID_aes_128_ctr:
|
||||
case NID_aes_192_ctr:
|
||||
case NID_aes_256_ctr:
|
||||
ret = drbg_ctr_init(drbg);
|
||||
break;
|
||||
}
|
||||
|
||||
if (ret == 0)
|
||||
RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/*
|
||||
* Allocate memory and initialize a new DRBG. The DRBG is allocated on
|
||||
* the secure heap if |secure| is nonzero and the secure heap is enabled.
|
||||
* The |parent|, if not NULL, will be used as random source for reseeding.
|
||||
*
|
||||
* Returns a pointer to the new DRBG instance on success, NULL on failure.
|
||||
*/
|
||||
static RAND_DRBG *rand_drbg_new(int secure,
|
||||
int type,
|
||||
unsigned int flags,
|
||||
RAND_DRBG *parent)
|
||||
{
|
||||
RAND_DRBG *drbg = secure ?
|
||||
OPENSSL_secure_zalloc(sizeof(*drbg)) : OPENSSL_zalloc(sizeof(*drbg));
|
||||
|
||||
if (drbg == NULL) {
|
||||
RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
|
||||
goto err;
|
||||
}
|
||||
|
||||
drbg->secure = secure && CRYPTO_secure_allocated(drbg);
|
||||
drbg->fork_count = rand_fork_count;
|
||||
drbg->parent = parent;
|
||||
if (RAND_DRBG_set(drbg, type, flags) == 0)
|
||||
goto err;
|
||||
|
||||
if (!RAND_DRBG_set_callbacks(drbg, rand_drbg_get_entropy,
|
||||
rand_drbg_cleanup_entropy,
|
||||
NULL, NULL))
|
||||
goto err;
|
||||
|
||||
return drbg;
|
||||
|
||||
err:
|
||||
if (drbg->secure)
|
||||
OPENSSL_secure_free(drbg);
|
||||
else
|
||||
OPENSSL_free(drbg);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
|
||||
{
|
||||
return rand_drbg_new(0, type, flags, parent);
|
||||
}
|
||||
|
||||
RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent)
|
||||
{
|
||||
return rand_drbg_new(1, type, flags, parent);
|
||||
}
|
||||
|
||||
/*
|
||||
* Uninstantiate |drbg| and free all memory.
|
||||
*/
|
||||
void RAND_DRBG_free(RAND_DRBG *drbg)
|
||||
{
|
||||
if (drbg == NULL)
|
||||
return;
|
||||
|
||||
if (drbg->meth != NULL)
|
||||
drbg->meth->uninstantiate(drbg);
|
||||
CRYPTO_THREAD_lock_free(drbg->lock);
|
||||
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
|
||||
|
||||
if (drbg->secure)
|
||||
OPENSSL_secure_clear_free(drbg, sizeof(*drbg));
|
||||
else
|
||||
OPENSSL_clear_free(drbg, sizeof(*drbg));
|
||||
}
|
||||
|
||||
/*
|
||||
* Instantiate |drbg|, after it has been initialized. Use |pers| and
|
||||
* |perslen| as prediction-resistance input.
|
||||
*
|
||||
* Requires that drbg->lock is already locked for write, if non-null.
|
||||
*
|
||||
* Returns 1 on success, 0 on failure.
|
||||
*/
|
||||
int RAND_DRBG_instantiate(RAND_DRBG *drbg,
|
||||
const unsigned char *pers, size_t perslen)
|
||||
{
|
||||
unsigned char *nonce = NULL, *entropy = NULL;
|
||||
size_t noncelen = 0, entropylen = 0;
|
||||
|
||||
if (perslen > drbg->max_perslen) {
|
||||
RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
|
||||
RAND_R_PERSONALISATION_STRING_TOO_LONG);
|
||||
goto end;
|
||||
}
|
||||
|
||||
if (drbg->meth == NULL)
|
||||
{
|
||||
RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
|
||||
RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
|
||||
goto end;
|
||||
}
|
||||
|
||||
if (drbg->state != DRBG_UNINITIALISED) {
|
||||
RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
|
||||
drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE
|
||||
: RAND_R_ALREADY_INSTANTIATED);
|
||||
goto end;
|
||||
}
|
||||
|
||||
drbg->state = DRBG_ERROR;
|
||||
if (drbg->get_entropy != NULL)
|
||||
entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
|
||||
drbg->min_entropylen, drbg->max_entropylen);
|
||||
if (entropylen < drbg->min_entropylen
|
||||
|| entropylen > drbg->max_entropylen) {
|
||||
RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
|
||||
goto end;
|
||||
}
|
||||
|
||||
if (drbg->max_noncelen > 0 && drbg->get_nonce != NULL) {
|
||||
noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
|
||||
drbg->min_noncelen, drbg->max_noncelen);
|
||||
if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
|
||||
RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
|
||||
RAND_R_ERROR_RETRIEVING_NONCE);
|
||||
goto end;
|
||||
}
|
||||
}
|
||||
|
||||
if (!drbg->meth->instantiate(drbg, entropy, entropylen,
|
||||
nonce, noncelen, pers, perslen)) {
|
||||
RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
|
||||
goto end;
|
||||
}
|
||||
|
||||
drbg->state = DRBG_READY;
|
||||
drbg->generate_counter = 0;
|
||||
drbg->reseed_time = time(NULL);
|
||||
if (drbg->reseed_counter > 0) {
|
||||
if (drbg->parent == NULL)
|
||||
drbg->reseed_counter++;
|
||||
else
|
||||
drbg->reseed_counter = drbg->parent->reseed_counter;
|
||||
}
|
||||
|
||||
end:
|
||||
if (entropy != NULL && drbg->cleanup_entropy != NULL)
|
||||
drbg->cleanup_entropy(drbg, entropy, entropylen);
|
||||
if (nonce != NULL && drbg->cleanup_nonce!= NULL )
|
||||
drbg->cleanup_nonce(drbg, nonce, noncelen);
|
||||
if (drbg->pool != NULL) {
|
||||
if (drbg->state == DRBG_READY) {
|
||||
RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
|
||||
RAND_R_ERROR_ENTROPY_POOL_WAS_IGNORED);
|
||||
drbg->state = DRBG_ERROR;
|
||||
}
|
||||
RAND_POOL_free(drbg->pool);
|
||||
drbg->pool = NULL;
|
||||
}
|
||||
if (drbg->state == DRBG_READY)
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Uninstantiate |drbg|. Must be instantiated before it can be used.
|
||||
*
|
||||
* Requires that drbg->lock is already locked for write, if non-null.
|
||||
*
|
||||
* Returns 1 on success, 0 on failure.
|
||||
*/
|
||||
int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
|
||||
{
|
||||
if (drbg->meth == NULL)
|
||||
{
|
||||
RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
|
||||
RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Clear the entire drbg->ctr struct, then reset some important
|
||||
* members of the drbg->ctr struct (e.g. keysize, df_ks) to their
|
||||
* initial values.
|
||||
*/
|
||||
drbg->meth->uninstantiate(drbg);
|
||||
return RAND_DRBG_set(drbg, drbg->nid, drbg->flags);
|
||||
}
|
||||
|
||||
/*
|
||||
* Reseed |drbg|, mixing in the specified data
|
||||
*
|
||||
* Requires that drbg->lock is already locked for write, if non-null.
|
||||
*
|
||||
* Returns 1 on success, 0 on failure.
|
||||
*/
|
||||
int RAND_DRBG_reseed(RAND_DRBG *drbg,
|
||||
const unsigned char *adin, size_t adinlen)
|
||||
{
|
||||
unsigned char *entropy = NULL;
|
||||
size_t entropylen = 0;
|
||||
|
||||
if (drbg->state == DRBG_ERROR) {
|
||||
RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
|
||||
return 0;
|
||||
}
|
||||
if (drbg->state == DRBG_UNINITIALISED) {
|
||||
RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (adin == NULL)
|
||||
adinlen = 0;
|
||||
else if (adinlen > drbg->max_adinlen) {
|
||||
RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
|
||||
return 0;
|
||||
}
|
||||
|
||||
drbg->state = DRBG_ERROR;
|
||||
if (drbg->get_entropy != NULL)
|
||||
entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
|
||||
drbg->min_entropylen, drbg->max_entropylen);
|
||||
if (entropylen < drbg->min_entropylen
|
||||
|| entropylen > drbg->max_entropylen) {
|
||||
RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
|
||||
goto end;
|
||||
}
|
||||
|
||||
if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
|
||||
goto end;
|
||||
|
||||
drbg->state = DRBG_READY;
|
||||
drbg->generate_counter = 0;
|
||||
drbg->reseed_time = time(NULL);
|
||||
if (drbg->reseed_counter > 0) {
|
||||
if (drbg->parent == NULL)
|
||||
drbg->reseed_counter++;
|
||||
else
|
||||
drbg->reseed_counter = drbg->parent->reseed_counter;
|
||||
}
|
||||
|
||||
end:
|
||||
if (entropy != NULL && drbg->cleanup_entropy != NULL)
|
||||
drbg->cleanup_entropy(drbg, entropy, entropylen);
|
||||
if (drbg->state == DRBG_READY)
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Restart |drbg|, using the specified entropy or additional input
|
||||
*
|
||||
* Tries its best to get the drbg instantiated by all means,
|
||||
* regardless of its current state.
|
||||
*
|
||||
* Optionally, a |buffer| of |len| random bytes can be passed,
|
||||
* which is assumed to contain at least |entropy| bits of entropy.
|
||||
*
|
||||
* If |entropy| > 0, the buffer content is used as entropy input.
|
||||
*
|
||||
* If |entropy| == 0, the buffer content is used as additional input
|
||||
*
|
||||
* Returns 1 on success, 0 on failure.
|
||||
*
|
||||
* This function is used internally only.
|
||||
*/
|
||||
int rand_drbg_restart(RAND_DRBG *drbg,
|
||||
const unsigned char *buffer, size_t len, size_t entropy)
|
||||
{
|
||||
int reseeded = 0;
|
||||
const unsigned char *adin = NULL;
|
||||
size_t adinlen = 0;
|
||||
|
||||
if (drbg->pool != NULL) {
|
||||
RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
|
||||
RAND_POOL_free(drbg->pool);
|
||||
drbg->pool = NULL;
|
||||
}
|
||||
|
||||
if (buffer != NULL) {
|
||||
if (entropy > 0) {
|
||||
if (drbg->max_entropylen < len) {
|
||||
RANDerr(RAND_F_RAND_DRBG_RESTART,
|
||||
RAND_R_ENTROPY_INPUT_TOO_LONG);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (entropy > 8 * len) {
|
||||
RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* will be picked up by the rand_drbg_get_entropy() callback */
|
||||
drbg->pool = RAND_POOL_new(entropy, len, len);
|
||||
if (drbg->pool == NULL)
|
||||
return 0;
|
||||
|
||||
RAND_POOL_add(drbg->pool, buffer, len, entropy);
|
||||
} else {
|
||||
if (drbg->max_adinlen < len) {
|
||||
RANDerr(RAND_F_RAND_DRBG_RESTART,
|
||||
RAND_R_ADDITIONAL_INPUT_TOO_LONG);
|
||||
return 0;
|
||||
}
|
||||
adin = buffer;
|
||||
adinlen = len;
|
||||
}
|
||||
}
|
||||
|
||||
/* repair error state */
|
||||
if (drbg->state == DRBG_ERROR)
|
||||
RAND_DRBG_uninstantiate(drbg);
|
||||
|
||||
/* repair uninitialized state */
|
||||
if (drbg->state == DRBG_UNINITIALISED) {
|
||||
/* reinstantiate drbg */
|
||||
RAND_DRBG_instantiate(drbg,
|
||||
(const unsigned char *) ossl_pers_string,
|
||||
sizeof(ossl_pers_string) - 1);
|
||||
/* already reseeded. prevent second reseeding below */
|
||||
reseeded = (drbg->state == DRBG_READY);
|
||||
}
|
||||
|
||||
/* refresh current state if entropy or additional input has been provided */
|
||||
if (drbg->state == DRBG_READY) {
|
||||
if (adin != NULL) {
|
||||
/*
|
||||
* mix in additional input without reseeding
|
||||
*
|
||||
* Similar to RAND_DRBG_reseed(), but the provided additional
|
||||
* data |adin| is mixed into the current state without pulling
|
||||
* entropy from the trusted entropy source using get_entropy().
|
||||
* This is not a reseeding in the strict sense of NIST SP 800-90A.
|
||||
*/
|
||||
drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
|
||||
} else if (reseeded == 0) {
|
||||
/* do a full reseeding if it has not been done yet above */
|
||||
RAND_DRBG_reseed(drbg, NULL, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* check whether a given entropy pool was cleared properly during reseed */
|
||||
if (drbg->pool != NULL) {
|
||||
drbg->state = DRBG_ERROR;
|
||||
RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
|
||||
RAND_POOL_free(drbg->pool);
|
||||
drbg->pool = NULL;
|
||||
return 0;
|
||||
}
|
||||
|
||||
return drbg->state == DRBG_READY;
|
||||
}
|
||||
|
||||
/*
|
||||
* Generate |outlen| bytes into the buffer at |out|. Reseed if we need
|
||||
* to or if |prediction_resistance| is set. Additional input can be
|
||||
* sent in |adin| and |adinlen|.
|
||||
*
|
||||
* Requires that drbg->lock is already locked for write, if non-null.
|
||||
*
|
||||
* Returns 1 on success, 0 on failure.
|
||||
*
|
||||
*/
|
||||
int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
|
||||
int prediction_resistance,
|
||||
const unsigned char *adin, size_t adinlen)
|
||||
{
|
||||
int reseed_required = 0;
|
||||
|
||||
if (drbg->state != DRBG_READY) {
|
||||
/* try to recover from previous errors */
|
||||
rand_drbg_restart(drbg, NULL, 0, 0);
|
||||
|
||||
if (drbg->state == DRBG_ERROR) {
|
||||
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
|
||||
return 0;
|
||||
}
|
||||
if (drbg->state == DRBG_UNINITIALISED) {
|
||||
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (outlen > drbg->max_request) {
|
||||
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
|
||||
return 0;
|
||||
}
|
||||
if (adinlen > drbg->max_adinlen) {
|
||||
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (drbg->fork_count != rand_fork_count) {
|
||||
drbg->fork_count = rand_fork_count;
|
||||
reseed_required = 1;
|
||||
}
|
||||
|
||||
if (drbg->reseed_interval > 0) {
|
||||
if (drbg->generate_counter >= drbg->reseed_interval)
|
||||
reseed_required = 1;
|
||||
}
|
||||
if (drbg->reseed_time_interval > 0) {
|
||||
time_t now = time(NULL);
|
||||
if (now < drbg->reseed_time
|
||||
|| now - drbg->reseed_time >= drbg->reseed_time_interval)
|
||||
reseed_required = 1;
|
||||
}
|
||||
if (drbg->reseed_counter > 0 && drbg->parent != NULL) {
|
||||
if (drbg->reseed_counter != drbg->parent->reseed_counter)
|
||||
reseed_required = 1;
|
||||
}
|
||||
|
||||
if (reseed_required || prediction_resistance) {
|
||||
if (!RAND_DRBG_reseed(drbg, adin, adinlen)) {
|
||||
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
|
||||
return 0;
|
||||
}
|
||||
adin = NULL;
|
||||
adinlen = 0;
|
||||
}
|
||||
|
||||
if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
|
||||
drbg->state = DRBG_ERROR;
|
||||
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
|
||||
return 0;
|
||||
}
|
||||
|
||||
drbg->generate_counter++;
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* Generates |outlen| random bytes and stores them in |out|. It will
|
||||
* using the given |drbg| to generate the bytes.
|
||||
*
|
||||
* Requires that drbg->lock is already locked for write, if non-null.
|
||||
*
|
||||
* Returns 1 on success 0 on failure.
|
||||
*/
|
||||
int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
|
||||
{
|
||||
unsigned char *additional = NULL;
|
||||
size_t additional_len;
|
||||
size_t chunk;
|
||||
size_t ret;
|
||||
|
||||
additional_len = rand_drbg_get_additional_data(&additional, drbg->max_adinlen);
|
||||
|
||||
for ( ; outlen > 0; outlen -= chunk, out += chunk) {
|
||||
chunk = outlen;
|
||||
if (chunk > drbg->max_request)
|
||||
chunk = drbg->max_request;
|
||||
ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
|
||||
if (!ret)
|
||||
goto err;
|
||||
}
|
||||
ret = 1;
|
||||
|
||||
err:
|
||||
if (additional_len != 0)
|
||||
OPENSSL_secure_clear_free(additional, additional_len);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set the RAND_DRBG callbacks for obtaining entropy and nonce.
|
||||
*
|
||||
* In the following, the signature and the semantics of the
|
||||
* get_entropy() and cleanup_entropy() callbacks are explained.
|
||||
*
|
||||
* GET_ENTROPY
|
||||
*
|
||||
* size_t get_entropy(RAND_DRBG *ctx,
|
||||
* unsigned char **pout,
|
||||
* int entropy,
|
||||
* size_t min_len, size_t max_len);
|
||||
*
|
||||
* This is a request to allocate and fill a buffer of size
|
||||
* |min_len| <= size <= |max_len| (in bytes) which contains
|
||||
* at least |entropy| bits of randomness. The buffer's address is
|
||||
* to be returned in |*pout| and the number of collected
|
||||
* randomness bytes (which may be less than the allocated size
|
||||
* of the buffer) as return value.
|
||||
*
|
||||
* If the callback fails to acquire at least |entropy| bits of
|
||||
* randomness, it shall return a buffer length of 0.
|
||||
*
|
||||
* CLEANUP_ENTROPY
|
||||
*
|
||||
* void cleanup_entropy(RAND_DRBG *ctx,
|
||||
* unsigned char *out, size_t outlen);
|
||||
*
|
||||
* A request to clear and free the buffer allocated by get_entropy().
|
||||
* The values |out| and |outlen| are expected to be the random buffer's
|
||||
* address and length, as returned by the get_entropy() callback.
|
||||
*
|
||||
* GET_NONCE, CLEANUP_NONCE
|
||||
*
|
||||
* Signature and semantics of the get_nonce() and cleanup_nonce()
|
||||
* callbacks are analogous to get_entropy() and cleanup_entropy().
|
||||
* Currently, the nonce is used only for the known answer tests.
|
||||
*/
|
||||
int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
|
||||
RAND_DRBG_get_entropy_fn get_entropy,
|
||||
RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
|
||||
RAND_DRBG_get_nonce_fn get_nonce,
|
||||
RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
|
||||
{
|
||||
if (drbg->state != DRBG_UNINITIALISED)
|
||||
return 0;
|
||||
drbg->get_entropy = get_entropy;
|
||||
drbg->cleanup_entropy = cleanup_entropy;
|
||||
drbg->get_nonce = get_nonce;
|
||||
drbg->cleanup_nonce = cleanup_nonce;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set the reseed interval.
|
||||
*
|
||||
* The drbg will reseed automatically whenever the number of generate
|
||||
* requests exceeds the given reseed interval. If the reseed interval
|
||||
* is 0, then this feature is disabled.
|
||||
*
|
||||
* Returns 1 on success, 0 on failure.
|
||||
*/
|
||||
int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
|
||||
{
|
||||
if (interval > MAX_RESEED_INTERVAL)
|
||||
return 0;
|
||||
drbg->reseed_interval = interval;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set the reseed time interval.
|
||||
*
|
||||
* The drbg will reseed automatically whenever the time elapsed since
|
||||
* the last reseeding exceeds the given reseed time interval. For safety,
|
||||
* a reseeding will also occur if the clock has been reset to a smaller
|
||||
* value.
|
||||
*
|
||||
* Returns 1 on success, 0 on failure.
|
||||
*/
|
||||
int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
|
||||
{
|
||||
if (interval > MAX_RESEED_TIME_INTERVAL)
|
||||
return 0;
|
||||
drbg->reseed_time_interval = interval;
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Locks the given drbg. Locking a drbg which does not have locking
|
||||
* enabled is considered a successful no-op.
|
||||
*
|
||||
* Returns 1 on success, 0 on failure.
|
||||
*/
|
||||
int rand_drbg_lock(RAND_DRBG *drbg)
|
||||
{
|
||||
if (drbg->lock != NULL)
|
||||
return CRYPTO_THREAD_write_lock(drbg->lock);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* Unlocks the given drbg. Unlocking a drbg which does not have locking
|
||||
* enabled is considered a successful no-op.
|
||||
*
|
||||
* Returns 1 on success, 0 on failure.
|
||||
*/
|
||||
int rand_drbg_unlock(RAND_DRBG *drbg)
|
||||
{
|
||||
if (drbg->lock != NULL)
|
||||
return CRYPTO_THREAD_unlock(drbg->lock);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* Enables locking for the given drbg
|
||||
*
|
||||
* Locking can only be enabled if the random generator
|
||||
* is in the uninitialized state.
|
||||
*
|
||||
* Returns 1 on success, 0 on failure.
|
||||
*/
|
||||
int rand_drbg_enable_locking(RAND_DRBG *drbg)
|
||||
{
|
||||
if (drbg->state != DRBG_UNINITIALISED) {
|
||||
RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
|
||||
RAND_R_DRBG_ALREADY_INITIALIZED);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (drbg->lock == NULL) {
|
||||
if (drbg->parent != NULL && drbg->parent->lock == NULL) {
|
||||
RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
|
||||
RAND_R_PARENT_LOCKING_NOT_ENABLED);
|
||||
return 0;
|
||||
}
|
||||
|
||||
drbg->lock = CRYPTO_THREAD_lock_new();
|
||||
if (drbg->lock == NULL) {
|
||||
RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
|
||||
RAND_R_FAILED_TO_CREATE_LOCK);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get and set the EXDATA
|
||||
*/
|
||||
int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
|
||||
{
|
||||
return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
|
||||
}
|
||||
|
||||
void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
|
||||
{
|
||||
return CRYPTO_get_ex_data(&drbg->ex_data, idx);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* The following functions provide a RAND_METHOD that works on the
|
||||
* global DRBG. They lock.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Allocates a new global DRBG on the secure heap (if enabled) and
|
||||
* initializes it with default settings.
|
||||
*
|
||||
* Returns a pointer to the new DRBG instance on success, NULL on failure.
|
||||
*/
|
||||
static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
|
||||
{
|
||||
RAND_DRBG *drbg;
|
||||
|
||||
drbg = RAND_DRBG_secure_new(RAND_DRBG_NID, 0, parent);
|
||||
if (drbg == NULL)
|
||||
return NULL;
|
||||
|
||||
if (rand_drbg_enable_locking(drbg) == 0)
|
||||
goto err;
|
||||
|
||||
if (parent == NULL) {
|
||||
drbg->reseed_interval = MASTER_RESEED_INTERVAL;
|
||||
drbg->reseed_time_interval = MASTER_RESEED_TIME_INTERVAL;
|
||||
} else {
|
||||
drbg->reseed_interval = SLAVE_RESEED_INTERVAL;
|
||||
drbg->reseed_time_interval = SLAVE_RESEED_TIME_INTERVAL;
|
||||
}
|
||||
|
||||
/* enable seed propagation */
|
||||
drbg->reseed_counter = 1;
|
||||
|
||||
/*
|
||||
* Ignore instantiation error so support just-in-time instantiation.
|
||||
*
|
||||
* The state of the drbg will be checked in RAND_DRBG_generate() and
|
||||
* an automatic recovery is attempted.
|
||||
*/
|
||||
RAND_DRBG_instantiate(drbg,
|
||||
(const unsigned char *) ossl_pers_string,
|
||||
sizeof(ossl_pers_string) - 1);
|
||||
return drbg;
|
||||
|
||||
err:
|
||||
RAND_DRBG_free(drbg);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
* Initialize the global DRBGs on first use.
|
||||
* Returns 1 on success, 0 on failure.
|
||||
*/
|
||||
DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
|
||||
{
|
||||
/*
|
||||
* ensure that libcrypto is initialized, otherwise the
|
||||
* DRBG locks are not cleaned up properly
|
||||
*/
|
||||
if (!OPENSSL_init_crypto(0, NULL))
|
||||
return 0;
|
||||
|
||||
drbg_master = drbg_setup(NULL);
|
||||
drbg_public = drbg_setup(drbg_master);
|
||||
drbg_private = drbg_setup(drbg_master);
|
||||
|
||||
if (drbg_master == NULL || drbg_public == NULL || drbg_private == NULL)
|
||||
return 0;
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Clean up the global DRBGs before exit */
|
||||
void rand_drbg_cleanup_int(void)
|
||||
{
|
||||
RAND_DRBG_free(drbg_private);
|
||||
RAND_DRBG_free(drbg_public);
|
||||
RAND_DRBG_free(drbg_master);
|
||||
|
||||
drbg_private = drbg_public = drbg_master = NULL;
|
||||
}
|
||||
|
||||
/* Implements the default OpenSSL RAND_bytes() method */
|
||||
static int drbg_bytes(unsigned char *out, int count)
|
||||
{
|
||||
int ret;
|
||||
RAND_DRBG *drbg = RAND_DRBG_get0_public();
|
||||
|
||||
if (drbg == NULL)
|
||||
return 0;
|
||||
|
||||
rand_drbg_lock(drbg);
|
||||
ret = RAND_DRBG_bytes(drbg, out, count);
|
||||
rand_drbg_unlock(drbg);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Implements the default OpenSSL RAND_add() method */
|
||||
static int drbg_add(const void *buf, int num, double randomness)
|
||||
{
|
||||
int ret = 0;
|
||||
RAND_DRBG *drbg = RAND_DRBG_get0_master();
|
||||
|
||||
if (drbg == NULL)
|
||||
return 0;
|
||||
|
||||
if (num < 0 || randomness < 0.0)
|
||||
return 0;
|
||||
|
||||
if (randomness > (double)drbg->max_entropylen) {
|
||||
/*
|
||||
* The purpose of this check is to bound |randomness| by a
|
||||
* relatively small value in order to prevent an integer
|
||||
* overflow when multiplying by 8 in the rand_drbg_restart()
|
||||
* call below.
|
||||
*/
|
||||
return 0;
|
||||
}
|
||||
|
||||
rand_drbg_lock(drbg);
|
||||
ret = rand_drbg_restart(drbg, buf,
|
||||
(size_t)(unsigned int)num,
|
||||
(size_t)(8*randomness));
|
||||
rand_drbg_unlock(drbg);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Implements the default OpenSSL RAND_seed() method */
|
||||
static int drbg_seed(const void *buf, int num)
|
||||
{
|
||||
return drbg_add(buf, num, num);
|
||||
}
|
||||
|
||||
/* Implements the default OpenSSL RAND_status() method */
|
||||
static int drbg_status(void)
|
||||
{
|
||||
int ret;
|
||||
RAND_DRBG *drbg = RAND_DRBG_get0_master();
|
||||
|
||||
if (drbg == NULL)
|
||||
return 0;
|
||||
|
||||
rand_drbg_lock(drbg);
|
||||
ret = drbg->state == DRBG_READY ? 1 : 0;
|
||||
rand_drbg_unlock(drbg);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the master DRBG.
|
||||
* Returns pointer to the DRBG on success, NULL on failure.
|
||||
*
|
||||
*/
|
||||
RAND_DRBG *RAND_DRBG_get0_master(void)
|
||||
{
|
||||
if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
|
||||
return NULL;
|
||||
|
||||
return drbg_master;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the public DRBG.
|
||||
* Returns pointer to the DRBG on success, NULL on failure.
|
||||
*/
|
||||
RAND_DRBG *RAND_DRBG_get0_public(void)
|
||||
{
|
||||
if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
|
||||
return NULL;
|
||||
|
||||
return drbg_public;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the private DRBG.
|
||||
* Returns pointer to the DRBG on success, NULL on failure.
|
||||
*/
|
||||
RAND_DRBG *RAND_DRBG_get0_private(void)
|
||||
{
|
||||
if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
|
||||
return NULL;
|
||||
|
||||
return drbg_private;
|
||||
}
|
||||
|
||||
RAND_METHOD rand_meth = {
|
||||
drbg_seed,
|
||||
drbg_bytes,
|
||||
NULL,
|
||||
drbg_add,
|
||||
drbg_bytes,
|
||||
drbg_status
|
||||
};
|
||||
|
||||
RAND_METHOD *RAND_OpenSSL(void)
|
||||
{
|
||||
return &rand_meth;
|
||||
}
|
||||
@@ -1,667 +0,0 @@
|
||||
/*
|
||||
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
|
||||
*
|
||||
* Licensed under the OpenSSL license (the "License"). You may not use
|
||||
* this file except in compliance with the License. You can obtain a copy
|
||||
* in the file LICENSE in the source distribution or at
|
||||
* https://www.openssl.org/source/license.html
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "e_os.h"
|
||||
|
||||
#if !(defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_DSPBIOS))
|
||||
# include <sys/time.h>
|
||||
#endif
|
||||
#if defined(OPENSSL_SYS_VXWORKS)
|
||||
# include <time.h>
|
||||
#endif
|
||||
|
||||
#include <openssl/opensslconf.h>
|
||||
#include <openssl/crypto.h>
|
||||
#include <openssl/rand.h>
|
||||
#include <openssl/async.h>
|
||||
#include "rand_lcl.h"
|
||||
|
||||
#include <openssl/err.h>
|
||||
|
||||
#include <internal/thread_once.h>
|
||||
|
||||
#ifdef OPENSSL_FIPS
|
||||
# include <openssl/fips.h>
|
||||
#endif
|
||||
|
||||
#ifdef BN_DEBUG
|
||||
# define PREDICT
|
||||
#endif
|
||||
|
||||
/* #define PREDICT 1 */
|
||||
|
||||
#define STATE_SIZE 1023
|
||||
static size_t state_num = 0, state_index = 0;
|
||||
static unsigned char state[STATE_SIZE + MD_DIGEST_LENGTH];
|
||||
static unsigned char md[MD_DIGEST_LENGTH];
|
||||
static long md_count[2] = { 0, 0 };
|
||||
|
||||
static double entropy = 0;
|
||||
static int initialized = 0;
|
||||
|
||||
static CRYPTO_RWLOCK *rand_lock = NULL;
|
||||
static CRYPTO_RWLOCK *rand_tmp_lock = NULL;
|
||||
static CRYPTO_ONCE rand_lock_init = CRYPTO_ONCE_STATIC_INIT;
|
||||
|
||||
/* May be set only when a thread holds rand_lock (to prevent double locking) */
|
||||
static unsigned int crypto_lock_rand = 0;
|
||||
/* access to locking_threadid is synchronized by rand_tmp_lock */
|
||||
/* valid iff crypto_lock_rand is set */
|
||||
static CRYPTO_THREAD_ID locking_threadid;
|
||||
|
||||
#ifdef PREDICT
|
||||
int rand_predictable = 0;
|
||||
#endif
|
||||
|
||||
static int rand_hw_seed(EVP_MD_CTX *ctx);
|
||||
|
||||
static void rand_cleanup(void);
|
||||
static int rand_seed(const void *buf, int num);
|
||||
static int rand_add(const void *buf, int num, double add_entropy);
|
||||
static int rand_bytes(unsigned char *buf, int num, int pseudo);
|
||||
static int rand_nopseudo_bytes(unsigned char *buf, int num);
|
||||
#if OPENSSL_API_COMPAT < 0x10100000L
|
||||
static int rand_pseudo_bytes(unsigned char *buf, int num);
|
||||
#endif
|
||||
static int rand_status(void);
|
||||
|
||||
static RAND_METHOD rand_meth = {
|
||||
rand_seed,
|
||||
rand_nopseudo_bytes,
|
||||
rand_cleanup,
|
||||
rand_add,
|
||||
#if OPENSSL_API_COMPAT < 0x10100000L
|
||||
rand_pseudo_bytes,
|
||||
#else
|
||||
NULL,
|
||||
#endif
|
||||
rand_status
|
||||
};
|
||||
|
||||
DEFINE_RUN_ONCE_STATIC(do_rand_lock_init)
|
||||
{
|
||||
OPENSSL_init_crypto(0, NULL);
|
||||
rand_lock = CRYPTO_THREAD_lock_new();
|
||||
rand_tmp_lock = CRYPTO_THREAD_lock_new();
|
||||
return rand_lock != NULL && rand_tmp_lock != NULL;
|
||||
}
|
||||
|
||||
RAND_METHOD *RAND_OpenSSL(void)
|
||||
{
|
||||
return (&rand_meth);
|
||||
}
|
||||
|
||||
static void rand_cleanup(void)
|
||||
{
|
||||
OPENSSL_cleanse(state, sizeof(state));
|
||||
state_num = 0;
|
||||
state_index = 0;
|
||||
OPENSSL_cleanse(md, MD_DIGEST_LENGTH);
|
||||
md_count[0] = 0;
|
||||
md_count[1] = 0;
|
||||
entropy = 0;
|
||||
initialized = 0;
|
||||
CRYPTO_THREAD_lock_free(rand_lock);
|
||||
CRYPTO_THREAD_lock_free(rand_tmp_lock);
|
||||
}
|
||||
|
||||
static int rand_add(const void *buf, int num, double add)
|
||||
{
|
||||
int i, j, k, st_idx;
|
||||
long md_c[2];
|
||||
unsigned char local_md[MD_DIGEST_LENGTH];
|
||||
EVP_MD_CTX *m;
|
||||
int do_not_lock;
|
||||
int rv = 0;
|
||||
|
||||
if (!num)
|
||||
return 1;
|
||||
|
||||
/*
|
||||
* (Based on the rand(3) manpage)
|
||||
*
|
||||
* The input is chopped up into units of 20 bytes (or less for
|
||||
* the last block). Each of these blocks is run through the hash
|
||||
* function as follows: The data passed to the hash function
|
||||
* is the current 'md', the same number of bytes from the 'state'
|
||||
* (the location determined by in incremented looping index) as
|
||||
* the current 'block', the new key data 'block', and 'count'
|
||||
* (which is incremented after each use).
|
||||
* The result of this is kept in 'md' and also xored into the
|
||||
* 'state' at the same locations that were used as input into the
|
||||
* hash function.
|
||||
*/
|
||||
|
||||
m = EVP_MD_CTX_new();
|
||||
if (m == NULL)
|
||||
goto err;
|
||||
|
||||
if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
|
||||
goto err;
|
||||
|
||||
/* check if we already have the lock */
|
||||
if (crypto_lock_rand) {
|
||||
CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
|
||||
CRYPTO_THREAD_read_lock(rand_tmp_lock);
|
||||
do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
|
||||
CRYPTO_THREAD_unlock(rand_tmp_lock);
|
||||
} else
|
||||
do_not_lock = 0;
|
||||
|
||||
if (!do_not_lock)
|
||||
CRYPTO_THREAD_write_lock(rand_lock);
|
||||
st_idx = state_index;
|
||||
|
||||
/*
|
||||
* use our own copies of the counters so that even if a concurrent thread
|
||||
* seeds with exactly the same data and uses the same subarray there's
|
||||
* _some_ difference
|
||||
*/
|
||||
md_c[0] = md_count[0];
|
||||
md_c[1] = md_count[1];
|
||||
|
||||
memcpy(local_md, md, sizeof(md));
|
||||
|
||||
/* state_index <= state_num <= STATE_SIZE */
|
||||
state_index += num;
|
||||
if (state_index >= STATE_SIZE) {
|
||||
state_index %= STATE_SIZE;
|
||||
state_num = STATE_SIZE;
|
||||
} else if (state_num < STATE_SIZE) {
|
||||
if (state_index > state_num)
|
||||
state_num = state_index;
|
||||
}
|
||||
/* state_index <= state_num <= STATE_SIZE */
|
||||
|
||||
/*
|
||||
* state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE] are what we
|
||||
* will use now, but other threads may use them as well
|
||||
*/
|
||||
|
||||
md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
|
||||
|
||||
if (!do_not_lock)
|
||||
CRYPTO_THREAD_unlock(rand_lock);
|
||||
|
||||
for (i = 0; i < num; i += MD_DIGEST_LENGTH) {
|
||||
j = (num - i);
|
||||
j = (j > MD_DIGEST_LENGTH) ? MD_DIGEST_LENGTH : j;
|
||||
|
||||
if (!MD_Init(m))
|
||||
goto err;
|
||||
if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
|
||||
goto err;
|
||||
k = (st_idx + j) - STATE_SIZE;
|
||||
if (k > 0) {
|
||||
if (!MD_Update(m, &(state[st_idx]), j - k))
|
||||
goto err;
|
||||
if (!MD_Update(m, &(state[0]), k))
|
||||
goto err;
|
||||
} else if (!MD_Update(m, &(state[st_idx]), j))
|
||||
goto err;
|
||||
|
||||
/* DO NOT REMOVE THE FOLLOWING CALL TO MD_Update()! */
|
||||
if (!MD_Update(m, buf, j))
|
||||
goto err;
|
||||
/*
|
||||
* We know that line may cause programs such as purify and valgrind
|
||||
* to complain about use of uninitialized data. The problem is not,
|
||||
* it's with the caller. Removing that line will make sure you get
|
||||
* really bad randomness and thereby other problems such as very
|
||||
* insecure keys.
|
||||
*/
|
||||
|
||||
if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
|
||||
goto err;
|
||||
if (!MD_Final(m, local_md))
|
||||
goto err;
|
||||
md_c[1]++;
|
||||
|
||||
buf = (const char *)buf + j;
|
||||
|
||||
for (k = 0; k < j; k++) {
|
||||
/*
|
||||
* Parallel threads may interfere with this, but always each byte
|
||||
* of the new state is the XOR of some previous value of its and
|
||||
* local_md (intermediate values may be lost). Alway using locking
|
||||
* could hurt performance more than necessary given that
|
||||
* conflicts occur only when the total seeding is longer than the
|
||||
* random state.
|
||||
*/
|
||||
state[st_idx++] ^= local_md[k];
|
||||
if (st_idx >= STATE_SIZE)
|
||||
st_idx = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (!do_not_lock)
|
||||
CRYPTO_THREAD_write_lock(rand_lock);
|
||||
/*
|
||||
* Don't just copy back local_md into md -- this could mean that other
|
||||
* thread's seeding remains without effect (except for the incremented
|
||||
* counter). By XORing it we keep at least as much entropy as fits into
|
||||
* md.
|
||||
*/
|
||||
for (k = 0; k < (int)sizeof(md); k++) {
|
||||
md[k] ^= local_md[k];
|
||||
}
|
||||
if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
|
||||
entropy += add;
|
||||
if (!do_not_lock)
|
||||
CRYPTO_THREAD_unlock(rand_lock);
|
||||
|
||||
rv = 1;
|
||||
err:
|
||||
EVP_MD_CTX_free(m);
|
||||
return rv;
|
||||
}
|
||||
|
||||
static int rand_seed(const void *buf, int num)
|
||||
{
|
||||
return rand_add(buf, num, (double)num);
|
||||
}
|
||||
|
||||
static int rand_bytes(unsigned char *buf, int num, int pseudo)
|
||||
{
|
||||
static volatile int stirred_pool = 0;
|
||||
int i, j, k;
|
||||
size_t num_ceil, st_idx, st_num;
|
||||
int ok;
|
||||
long md_c[2];
|
||||
unsigned char local_md[MD_DIGEST_LENGTH];
|
||||
EVP_MD_CTX *m;
|
||||
#ifndef GETPID_IS_MEANINGLESS
|
||||
pid_t curr_pid = getpid();
|
||||
#endif
|
||||
time_t curr_time = time(NULL);
|
||||
int do_stir_pool = 0;
|
||||
/* time value for various platforms */
|
||||
#ifdef OPENSSL_SYS_WIN32
|
||||
FILETIME tv;
|
||||
# ifdef _WIN32_WCE
|
||||
SYSTEMTIME t;
|
||||
GetSystemTime(&t);
|
||||
SystemTimeToFileTime(&t, &tv);
|
||||
# else
|
||||
GetSystemTimeAsFileTime(&tv);
|
||||
# endif
|
||||
#elif defined(OPENSSL_SYS_VXWORKS)
|
||||
struct timespec tv;
|
||||
clock_gettime(CLOCK_REALTIME, &ts);
|
||||
#elif defined(OPENSSL_SYS_DSPBIOS)
|
||||
unsigned long long tv, OPENSSL_rdtsc();
|
||||
tv = OPENSSL_rdtsc();
|
||||
#else
|
||||
struct timeval tv;
|
||||
gettimeofday(&tv, NULL);
|
||||
#endif
|
||||
|
||||
#ifdef PREDICT
|
||||
if (rand_predictable) {
|
||||
static unsigned char val = 0;
|
||||
|
||||
for (i = 0; i < num; i++)
|
||||
buf[i] = val++;
|
||||
return (1);
|
||||
}
|
||||
#endif
|
||||
|
||||
if (num <= 0)
|
||||
return 1;
|
||||
|
||||
m = EVP_MD_CTX_new();
|
||||
if (m == NULL)
|
||||
goto err_mem;
|
||||
|
||||
/* round upwards to multiple of MD_DIGEST_LENGTH/2 */
|
||||
num_ceil =
|
||||
(1 + (num - 1) / (MD_DIGEST_LENGTH / 2)) * (MD_DIGEST_LENGTH / 2);
|
||||
|
||||
/*
|
||||
* (Based on the rand(3) manpage:)
|
||||
*
|
||||
* For each group of 10 bytes (or less), we do the following:
|
||||
*
|
||||
* Input into the hash function the local 'md' (which is initialized from
|
||||
* the global 'md' before any bytes are generated), the bytes that are to
|
||||
* be overwritten by the random bytes, and bytes from the 'state'
|
||||
* (incrementing looping index). From this digest output (which is kept
|
||||
* in 'md'), the top (up to) 10 bytes are returned to the caller and the
|
||||
* bottom 10 bytes are xored into the 'state'.
|
||||
*
|
||||
* Finally, after we have finished 'num' random bytes for the
|
||||
* caller, 'count' (which is incremented) and the local and global 'md'
|
||||
* are fed into the hash function and the results are kept in the
|
||||
* global 'md'.
|
||||
*/
|
||||
|
||||
if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
|
||||
goto err_mem;
|
||||
|
||||
CRYPTO_THREAD_write_lock(rand_lock);
|
||||
/*
|
||||
* We could end up in an async engine while holding this lock so ensure
|
||||
* we don't pause and cause a deadlock
|
||||
*/
|
||||
ASYNC_block_pause();
|
||||
|
||||
/* prevent rand_bytes() from trying to obtain the lock again */
|
||||
CRYPTO_THREAD_write_lock(rand_tmp_lock);
|
||||
locking_threadid = CRYPTO_THREAD_get_current_id();
|
||||
CRYPTO_THREAD_unlock(rand_tmp_lock);
|
||||
crypto_lock_rand = 1;
|
||||
|
||||
if (!initialized) {
|
||||
RAND_poll();
|
||||
initialized = 1;
|
||||
}
|
||||
|
||||
if (!stirred_pool)
|
||||
do_stir_pool = 1;
|
||||
|
||||
ok = (entropy >= ENTROPY_NEEDED);
|
||||
if (!ok) {
|
||||
/*
|
||||
* If the PRNG state is not yet unpredictable, then seeing the PRNG
|
||||
* output may help attackers to determine the new state; thus we have
|
||||
* to decrease the entropy estimate. Once we've had enough initial
|
||||
* seeding we don't bother to adjust the entropy count, though,
|
||||
* because we're not ambitious to provide *information-theoretic*
|
||||
* randomness. NOTE: This approach fails if the program forks before
|
||||
* we have enough entropy. Entropy should be collected in a separate
|
||||
* input pool and be transferred to the output pool only when the
|
||||
* entropy limit has been reached.
|
||||
*/
|
||||
entropy -= num;
|
||||
if (entropy < 0)
|
||||
entropy = 0;
|
||||
}
|
||||
|
||||
if (do_stir_pool) {
|
||||
/*
|
||||
* In the output function only half of 'md' remains secret, so we
|
||||
* better make sure that the required entropy gets 'evenly
|
||||
* distributed' through 'state', our randomness pool. The input
|
||||
* function (rand_add) chains all of 'md', which makes it more
|
||||
* suitable for this purpose.
|
||||
*/
|
||||
|
||||
int n = STATE_SIZE; /* so that the complete pool gets accessed */
|
||||
while (n > 0) {
|
||||
#if MD_DIGEST_LENGTH > 20
|
||||
# error "Please adjust DUMMY_SEED."
|
||||
#endif
|
||||
#define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
|
||||
/*
|
||||
* Note that the seed does not matter, it's just that
|
||||
* rand_add expects to have something to hash.
|
||||
*/
|
||||
rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
|
||||
n -= MD_DIGEST_LENGTH;
|
||||
}
|
||||
if (ok)
|
||||
stirred_pool = 1;
|
||||
}
|
||||
|
||||
st_idx = state_index;
|
||||
st_num = state_num;
|
||||
md_c[0] = md_count[0];
|
||||
md_c[1] = md_count[1];
|
||||
memcpy(local_md, md, sizeof(md));
|
||||
|
||||
state_index += num_ceil;
|
||||
if (state_index > state_num)
|
||||
state_index %= state_num;
|
||||
|
||||
/*
|
||||
* state[st_idx], ..., state[(st_idx + num_ceil - 1) % st_num] are now
|
||||
* ours (but other threads may use them too)
|
||||
*/
|
||||
|
||||
md_count[0] += 1;
|
||||
|
||||
/* before unlocking, we must clear 'crypto_lock_rand' */
|
||||
crypto_lock_rand = 0;
|
||||
ASYNC_unblock_pause();
|
||||
CRYPTO_THREAD_unlock(rand_lock);
|
||||
|
||||
while (num > 0) {
|
||||
/* num_ceil -= MD_DIGEST_LENGTH/2 */
|
||||
j = (num >= MD_DIGEST_LENGTH / 2) ? MD_DIGEST_LENGTH / 2 : num;
|
||||
num -= j;
|
||||
if (!MD_Init(m))
|
||||
goto err;
|
||||
#ifndef GETPID_IS_MEANINGLESS
|
||||
if (curr_pid) { /* just in the first iteration to save time */
|
||||
if (!MD_Update(m, (unsigned char *)&curr_pid, sizeof(curr_pid)))
|
||||
goto err;
|
||||
curr_pid = 0;
|
||||
}
|
||||
#endif
|
||||
if (curr_time) { /* just in the first iteration to save time */
|
||||
if (!MD_Update(m, (unsigned char *)&curr_time, sizeof(curr_time)))
|
||||
goto err;
|
||||
if (!MD_Update(m, (unsigned char *)&tv, sizeof(tv)))
|
||||
goto err;
|
||||
curr_time = 0;
|
||||
if (!rand_hw_seed(m))
|
||||
goto err;
|
||||
}
|
||||
if (!MD_Update(m, local_md, MD_DIGEST_LENGTH))
|
||||
goto err;
|
||||
if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c)))
|
||||
goto err;
|
||||
|
||||
k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num;
|
||||
if (k > 0) {
|
||||
if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k))
|
||||
goto err;
|
||||
if (!MD_Update(m, &(state[0]), k))
|
||||
goto err;
|
||||
} else if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2))
|
||||
goto err;
|
||||
if (!MD_Final(m, local_md))
|
||||
goto err;
|
||||
|
||||
for (i = 0; i < MD_DIGEST_LENGTH / 2; i++) {
|
||||
/* may compete with other threads */
|
||||
state[st_idx++] ^= local_md[i];
|
||||
if (st_idx >= st_num)
|
||||
st_idx = 0;
|
||||
if (i < j)
|
||||
*(buf++) = local_md[i + MD_DIGEST_LENGTH / 2];
|
||||
}
|
||||
}
|
||||
|
||||
if (!MD_Init(m)
|
||||
|| !MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))
|
||||
|| !MD_Update(m, local_md, MD_DIGEST_LENGTH))
|
||||
goto err;
|
||||
CRYPTO_THREAD_write_lock(rand_lock);
|
||||
/*
|
||||
* Prevent deadlocks if we end up in an async engine
|
||||
*/
|
||||
ASYNC_block_pause();
|
||||
if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) {
|
||||
ASYNC_unblock_pause();
|
||||
CRYPTO_THREAD_unlock(rand_lock);
|
||||
goto err;
|
||||
}
|
||||
ASYNC_unblock_pause();
|
||||
CRYPTO_THREAD_unlock(rand_lock);
|
||||
|
||||
EVP_MD_CTX_free(m);
|
||||
if (ok)
|
||||
return (1);
|
||||
else if (pseudo)
|
||||
return 0;
|
||||
else {
|
||||
RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED);
|
||||
ERR_add_error_data(1, "You need to read the OpenSSL FAQ, "
|
||||
"https://www.openssl.org/docs/faq.html");
|
||||
return (0);
|
||||
}
|
||||
err:
|
||||
RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB);
|
||||
EVP_MD_CTX_free(m);
|
||||
return 0;
|
||||
err_mem:
|
||||
RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE);
|
||||
EVP_MD_CTX_free(m);
|
||||
return 0;
|
||||
|
||||
}
|
||||
|
||||
static int rand_nopseudo_bytes(unsigned char *buf, int num)
|
||||
{
|
||||
return rand_bytes(buf, num, 0);
|
||||
}
|
||||
|
||||
#if OPENSSL_API_COMPAT < 0x10100000L
|
||||
/*
|
||||
* pseudo-random bytes that are guaranteed to be unique but not unpredictable
|
||||
*/
|
||||
static int rand_pseudo_bytes(unsigned char *buf, int num)
|
||||
{
|
||||
return rand_bytes(buf, num, 1);
|
||||
}
|
||||
#endif
|
||||
|
||||
static int rand_status(void)
|
||||
{
|
||||
CRYPTO_THREAD_ID cur;
|
||||
int ret;
|
||||
int do_not_lock;
|
||||
|
||||
if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
|
||||
return 0;
|
||||
|
||||
cur = CRYPTO_THREAD_get_current_id();
|
||||
/*
|
||||
* check if we already have the lock (could happen if a RAND_poll()
|
||||
* implementation calls RAND_status())
|
||||
*/
|
||||
if (crypto_lock_rand) {
|
||||
CRYPTO_THREAD_read_lock(rand_tmp_lock);
|
||||
do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur);
|
||||
CRYPTO_THREAD_unlock(rand_tmp_lock);
|
||||
} else
|
||||
do_not_lock = 0;
|
||||
|
||||
if (!do_not_lock) {
|
||||
CRYPTO_THREAD_write_lock(rand_lock);
|
||||
/*
|
||||
* Prevent deadlocks in case we end up in an async engine
|
||||
*/
|
||||
ASYNC_block_pause();
|
||||
|
||||
/*
|
||||
* prevent rand_bytes() from trying to obtain the lock again
|
||||
*/
|
||||
CRYPTO_THREAD_write_lock(rand_tmp_lock);
|
||||
locking_threadid = cur;
|
||||
CRYPTO_THREAD_unlock(rand_tmp_lock);
|
||||
crypto_lock_rand = 1;
|
||||
}
|
||||
|
||||
if (!initialized) {
|
||||
RAND_poll();
|
||||
initialized = 1;
|
||||
}
|
||||
|
||||
ret = entropy >= ENTROPY_NEEDED;
|
||||
|
||||
if (!do_not_lock) {
|
||||
/* before unlocking, we must clear 'crypto_lock_rand' */
|
||||
crypto_lock_rand = 0;
|
||||
|
||||
ASYNC_unblock_pause();
|
||||
CRYPTO_THREAD_unlock(rand_lock);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/*
|
||||
* rand_hw_seed: get seed data from any available hardware RNG. only
|
||||
* currently supports rdrand.
|
||||
*/
|
||||
|
||||
/* Adapted from eng_rdrand.c */
|
||||
|
||||
#if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
|
||||
defined(__x86_64) || defined(__x86_64__) || \
|
||||
defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \
|
||||
&& !defined(OPENSSL_NO_RDRAND)
|
||||
|
||||
# define RDRAND_CALLS 4
|
||||
|
||||
size_t OPENSSL_ia32_rdrand(void);
|
||||
extern unsigned int OPENSSL_ia32cap_P[];
|
||||
|
||||
static int rand_hw_seed(EVP_MD_CTX *ctx)
|
||||
{
|
||||
int i;
|
||||
if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
|
||||
return 1;
|
||||
for (i = 0; i < RDRAND_CALLS; i++) {
|
||||
size_t rnd;
|
||||
rnd = OPENSSL_ia32_rdrand();
|
||||
if (rnd == 0)
|
||||
return 1;
|
||||
if (!MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t)))
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* XOR an existing buffer with random data */
|
||||
|
||||
void rand_hw_xor(unsigned char *buf, size_t num)
|
||||
{
|
||||
size_t rnd;
|
||||
if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32))))
|
||||
return;
|
||||
while (num >= sizeof(size_t)) {
|
||||
rnd = OPENSSL_ia32_rdrand();
|
||||
if (rnd == 0)
|
||||
return;
|
||||
*((size_t *)buf) ^= rnd;
|
||||
buf += sizeof(size_t);
|
||||
num -= sizeof(size_t);
|
||||
}
|
||||
if (num) {
|
||||
rnd = OPENSSL_ia32_rdrand();
|
||||
if (rnd == 0)
|
||||
return;
|
||||
while (num) {
|
||||
*buf ^= rnd & 0xff;
|
||||
rnd >>= 8;
|
||||
buf++;
|
||||
num--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
static int rand_hw_seed(EVP_MD_CTX *ctx)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
void rand_hw_xor(unsigned char *buf, size_t num)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
#endif
|
||||
+71
-161
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
|
||||
* Copyright 2000-2017 The OpenSSL Project Authors. All Rights Reserved.
|
||||
*
|
||||
* Licensed under the OpenSSL license (the "License"). You may not use
|
||||
* this file except in compliance with the License. You can obtain a copy
|
||||
@@ -16,59 +16,28 @@ NON_EMPTY_TRANSLATION_UNIT
|
||||
# include <openssl/e_os2.h>
|
||||
# include <openssl/rand.h>
|
||||
|
||||
/*-
|
||||
* Query the EGD <URL: http://www.lothar.com/tech/crypto/>.
|
||||
*
|
||||
* This module supplies three routines:
|
||||
*
|
||||
* RAND_query_egd_bytes(path, buf, bytes)
|
||||
* will actually query "bytes" bytes of entropy form the egd-socket located
|
||||
* at path and will write them to buf (if supplied) or will directly feed
|
||||
* it to RAND_seed() if buf==NULL.
|
||||
* The number of bytes is not limited by the maximum chunk size of EGD,
|
||||
* which is 255 bytes. If more than 255 bytes are wanted, several chunks
|
||||
* of entropy bytes are requested. The connection is left open until the
|
||||
* query is competed.
|
||||
* RAND_query_egd_bytes() returns with
|
||||
* -1 if an error occurred during connection or communication.
|
||||
* num the number of bytes read from the EGD socket. This number is either
|
||||
* the number of bytes requested or smaller, if the EGD pool is
|
||||
* drained and the daemon signals that the pool is empty.
|
||||
* This routine does not touch any RAND_status(). This is necessary, since
|
||||
* PRNG functions may call it during initialization.
|
||||
*
|
||||
* RAND_egd_bytes(path, bytes) will query "bytes" bytes and have them
|
||||
* used to seed the PRNG.
|
||||
* RAND_egd_bytes() is a wrapper for RAND_query_egd_bytes() with buf=NULL.
|
||||
* Unlike RAND_query_egd_bytes(), RAND_status() is used to test the
|
||||
* seed status so that the return value can reflect the seed state:
|
||||
* -1 if an error occurred during connection or communication _or_
|
||||
* if the PRNG has still not received the required seeding.
|
||||
* num the number of bytes read from the EGD socket. This number is either
|
||||
* the number of bytes requested or smaller, if the EGD pool is
|
||||
* drained and the daemon signals that the pool is empty.
|
||||
*
|
||||
* RAND_egd(path) will query 255 bytes and use the bytes retrieved to seed
|
||||
* the PRNG.
|
||||
* RAND_egd() is a wrapper for RAND_egd_bytes() with numbytes=255.
|
||||
/*
|
||||
* Query an EGD
|
||||
*/
|
||||
|
||||
# if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_VOS) || defined(OPENSSL_SYS_UEFI)
|
||||
int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes)
|
||||
{
|
||||
return (-1);
|
||||
return -1;
|
||||
}
|
||||
|
||||
int RAND_egd(const char *path)
|
||||
{
|
||||
return (-1);
|
||||
return -1;
|
||||
}
|
||||
|
||||
int RAND_egd_bytes(const char *path, int bytes)
|
||||
{
|
||||
return (-1);
|
||||
return -1;
|
||||
}
|
||||
|
||||
# else
|
||||
|
||||
# include <openssl/opensslconf.h>
|
||||
# include OPENSSL_UNISTD
|
||||
# include <stddef.h>
|
||||
@@ -91,157 +60,98 @@ struct sockaddr_un {
|
||||
|
||||
int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes)
|
||||
{
|
||||
int ret = 0;
|
||||
FILE *fp = NULL;
|
||||
struct sockaddr_un addr;
|
||||
int len, num, numbytes;
|
||||
int fd = -1;
|
||||
int success;
|
||||
unsigned char egdbuf[2], tempbuf[255], *retrievebuf;
|
||||
int mybuffer, ret = -1, i, numbytes, fd;
|
||||
unsigned char tempbuf[255];
|
||||
|
||||
if (bytes > (int)sizeof(tempbuf))
|
||||
return -1;
|
||||
|
||||
/* Make socket. */
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sun_family = AF_UNIX;
|
||||
if (strlen(path) >= sizeof(addr.sun_path))
|
||||
return (-1);
|
||||
OPENSSL_strlcpy(addr.sun_path, path, sizeof(addr.sun_path));
|
||||
len = offsetof(struct sockaddr_un, sun_path) + strlen(path);
|
||||
return -1;
|
||||
strcpy(addr.sun_path, path);
|
||||
i = offsetof(struct sockaddr_un, sun_path) + strlen(path);
|
||||
fd = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
if (fd == -1)
|
||||
return (-1);
|
||||
success = 0;
|
||||
while (!success) {
|
||||
if (connect(fd, (struct sockaddr *)&addr, len) == 0)
|
||||
success = 1;
|
||||
else {
|
||||
switch (errno) {
|
||||
if (fd == -1 || (fp = fdopen(fd, "r+")) == NULL)
|
||||
return -1;
|
||||
setbuf(fp, NULL);
|
||||
|
||||
/* Try to connect */
|
||||
for ( ; ; ) {
|
||||
if (connect(fd, (struct sockaddr *)&addr, i) == 0)
|
||||
break;
|
||||
# ifdef EISCONN
|
||||
if (errno == EISCONN)
|
||||
break;
|
||||
# endif
|
||||
switch (errno) {
|
||||
# ifdef EINTR
|
||||
case EINTR:
|
||||
case EINTR:
|
||||
# endif
|
||||
# ifdef EAGAIN
|
||||
case EAGAIN:
|
||||
case EAGAIN:
|
||||
# endif
|
||||
# ifdef EINPROGRESS
|
||||
case EINPROGRESS:
|
||||
case EINPROGRESS:
|
||||
# endif
|
||||
# ifdef EALREADY
|
||||
case EALREADY:
|
||||
case EALREADY:
|
||||
# endif
|
||||
/* No error, try again */
|
||||
break;
|
||||
# ifdef EISCONN
|
||||
case EISCONN:
|
||||
success = 1;
|
||||
break;
|
||||
# endif
|
||||
default:
|
||||
ret = -1;
|
||||
goto err; /* failure */
|
||||
}
|
||||
/* No error, try again */
|
||||
break;
|
||||
default:
|
||||
ret = -1;
|
||||
goto err;
|
||||
}
|
||||
}
|
||||
|
||||
while (bytes > 0) {
|
||||
egdbuf[0] = 1;
|
||||
egdbuf[1] = bytes < 255 ? bytes : 255;
|
||||
numbytes = 0;
|
||||
while (numbytes != 2) {
|
||||
num = write(fd, egdbuf + numbytes, 2 - numbytes);
|
||||
if (num >= 0)
|
||||
numbytes += num;
|
||||
else {
|
||||
switch (errno) {
|
||||
# ifdef EINTR
|
||||
case EINTR:
|
||||
# endif
|
||||
# ifdef EAGAIN
|
||||
case EAGAIN:
|
||||
# endif
|
||||
/* No error, try again */
|
||||
break;
|
||||
default:
|
||||
ret = -1;
|
||||
goto err; /* failure */
|
||||
}
|
||||
}
|
||||
}
|
||||
numbytes = 0;
|
||||
while (numbytes != 1) {
|
||||
num = read(fd, egdbuf, 1);
|
||||
if (num == 0)
|
||||
goto err; /* descriptor closed */
|
||||
else if (num > 0)
|
||||
numbytes += num;
|
||||
else {
|
||||
switch (errno) {
|
||||
# ifdef EINTR
|
||||
case EINTR:
|
||||
# endif
|
||||
# ifdef EAGAIN
|
||||
case EAGAIN:
|
||||
# endif
|
||||
/* No error, try again */
|
||||
break;
|
||||
default:
|
||||
ret = -1;
|
||||
goto err; /* failure */
|
||||
}
|
||||
}
|
||||
}
|
||||
if (egdbuf[0] == 0)
|
||||
goto err;
|
||||
if (buf)
|
||||
retrievebuf = buf + ret;
|
||||
else
|
||||
retrievebuf = tempbuf;
|
||||
numbytes = 0;
|
||||
while (numbytes != egdbuf[0]) {
|
||||
num = read(fd, retrievebuf + numbytes, egdbuf[0] - numbytes);
|
||||
if (num == 0)
|
||||
goto err; /* descriptor closed */
|
||||
else if (num > 0)
|
||||
numbytes += num;
|
||||
else {
|
||||
switch (errno) {
|
||||
# ifdef EINTR
|
||||
case EINTR:
|
||||
# endif
|
||||
# ifdef EAGAIN
|
||||
case EAGAIN:
|
||||
# endif
|
||||
/* No error, try again */
|
||||
break;
|
||||
default:
|
||||
ret = -1;
|
||||
goto err; /* failure */
|
||||
}
|
||||
}
|
||||
}
|
||||
ret += egdbuf[0];
|
||||
bytes -= egdbuf[0];
|
||||
if (!buf)
|
||||
RAND_seed(tempbuf, egdbuf[0]);
|
||||
}
|
||||
/* Make request, see how many bytes we can get back. */
|
||||
tempbuf[0] = 1;
|
||||
tempbuf[1] = bytes;
|
||||
if (fwrite(tempbuf, sizeof(char), 2, fp) != 2 || fflush(fp) == EOF)
|
||||
goto err;
|
||||
if (fread(tempbuf, sizeof(char), 1, fp) != 1 || tempbuf[0] == 0)
|
||||
goto err;
|
||||
numbytes = tempbuf[0];
|
||||
|
||||
/* Which buffer are we using? */
|
||||
mybuffer = buf == NULL;
|
||||
if (mybuffer)
|
||||
buf = tempbuf;
|
||||
|
||||
/* Read bytes. */
|
||||
i = fread(buf, sizeof(char), numbytes, fp);
|
||||
if (i < numbytes)
|
||||
goto err;
|
||||
ret = numbytes;
|
||||
if (mybuffer)
|
||||
RAND_add(tempbuf, i, i);
|
||||
|
||||
err:
|
||||
if (fd != -1)
|
||||
close(fd);
|
||||
return (ret);
|
||||
if (fp != NULL)
|
||||
fclose(fp);
|
||||
return ret;
|
||||
}
|
||||
|
||||
int RAND_egd_bytes(const char *path, int bytes)
|
||||
{
|
||||
int num, ret = -1;
|
||||
int num;
|
||||
|
||||
num = RAND_query_egd_bytes(path, NULL, bytes);
|
||||
if (num < 0)
|
||||
goto err;
|
||||
if (RAND_status() == 1)
|
||||
ret = num;
|
||||
err:
|
||||
return (ret);
|
||||
return -1;
|
||||
if (RAND_status() != 1)
|
||||
return -1;
|
||||
return num;
|
||||
}
|
||||
|
||||
int RAND_egd(const char *path)
|
||||
{
|
||||
return (RAND_egd_bytes(path, 255));
|
||||
return RAND_egd_bytes(path, 255);
|
||||
}
|
||||
|
||||
# endif
|
||||
|
||||
+85
-14
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
* Generated by util/mkerr.pl DO NOT EDIT
|
||||
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
|
||||
* Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
|
||||
*
|
||||
* Licensed under the OpenSSL license (the "License"). You may not use
|
||||
* this file except in compliance with the License. You can obtain a copy
|
||||
@@ -8,23 +8,95 @@
|
||||
* https://www.openssl.org/source/license.html
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/rand.h>
|
||||
#include <openssl/randerr.h>
|
||||
|
||||
/* BEGIN ERROR CODES */
|
||||
#ifndef OPENSSL_NO_ERR
|
||||
|
||||
# define ERR_FUNC(func) ERR_PACK(ERR_LIB_RAND,func,0)
|
||||
# define ERR_REASON(reason) ERR_PACK(ERR_LIB_RAND,0,reason)
|
||||
|
||||
static ERR_STRING_DATA RAND_str_functs[] = {
|
||||
{ERR_FUNC(RAND_F_RAND_BYTES), "RAND_bytes"},
|
||||
static const ERR_STRING_DATA RAND_str_functs[] = {
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_DRBG_BYTES, 0), "drbg_bytes"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_DRBG_GET_ENTROPY, 0), "drbg_get_entropy"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_DRBG_SETUP, 0), "drbg_setup"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_GET_ENTROPY, 0), "get_entropy"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_BYTES, 0), "RAND_bytes"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_ENABLE_LOCKING, 0),
|
||||
"rand_drbg_enable_locking"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_GENERATE, 0),
|
||||
"RAND_DRBG_generate"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_INSTANTIATE, 0),
|
||||
"RAND_DRBG_instantiate"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_NEW, 0), "RAND_DRBG_new"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_RESEED, 0), "RAND_DRBG_reseed"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_RESTART, 0), "rand_drbg_restart"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_SET, 0), "RAND_DRBG_set"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_UNINSTANTIATE, 0),
|
||||
"RAND_DRBG_uninstantiate"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_LOAD_FILE, 0), "RAND_load_file"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_POOL_ADD, 0), "RAND_POOL_add"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_POOL_ADD_BEGIN, 0),
|
||||
"RAND_POOL_add_begin"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_POOL_ADD_END, 0), "RAND_POOL_add_end"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_POOL_BYTES_NEEDED, 0),
|
||||
"RAND_POOL_bytes_needed"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_POOL_NEW, 0), "RAND_POOL_new"},
|
||||
{ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_WRITE_FILE, 0), "RAND_write_file"},
|
||||
{0, NULL}
|
||||
};
|
||||
|
||||
static ERR_STRING_DATA RAND_str_reasons[] = {
|
||||
{ERR_REASON(RAND_R_PRNG_NOT_SEEDED), "PRNG not seeded"},
|
||||
static const ERR_STRING_DATA RAND_str_reasons[] = {
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ADDITIONAL_INPUT_TOO_LONG),
|
||||
"additional input too long"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ALREADY_INSTANTIATED),
|
||||
"already instantiated"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ARGUMENT_OUT_OF_RANGE),
|
||||
"argument out of range"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_CANNOT_OPEN_FILE), "Cannot open file"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_DRBG_ALREADY_INITIALIZED),
|
||||
"drbg already initialized"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_DRBG_NOT_INITIALISED),
|
||||
"drbg not initialised"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ENTROPY_INPUT_TOO_LONG),
|
||||
"entropy input too long"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ENTROPY_OUT_OF_RANGE),
|
||||
"entropy out of range"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_ENTROPY_POOL_WAS_IGNORED),
|
||||
"error entropy pool was ignored"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_INITIALISING_DRBG),
|
||||
"error initialising drbg"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_INSTANTIATING_DRBG),
|
||||
"error instantiating drbg"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_RETRIEVING_ADDITIONAL_INPUT),
|
||||
"error retrieving additional input"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_RETRIEVING_ENTROPY),
|
||||
"error retrieving entropy"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_RETRIEVING_NONCE),
|
||||
"error retrieving nonce"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_FAILED_TO_CREATE_LOCK),
|
||||
"failed to create lock"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_FUNC_NOT_IMPLEMENTED),
|
||||
"Function not implemented"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_FWRITE_ERROR), "Error writing file"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_GENERATE_ERROR), "generate error"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_INTERNAL_ERROR), "internal error"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_IN_ERROR_STATE), "in error state"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_NOT_A_REGULAR_FILE),
|
||||
"Not a regular file"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_NOT_INSTANTIATED), "not instantiated"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED),
|
||||
"no drbg implementation selected"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PARENT_LOCKING_NOT_ENABLED),
|
||||
"parent locking not enabled"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PERSONALISATION_STRING_TOO_LONG),
|
||||
"personalisation string too long"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PRNG_NOT_SEEDED), "PRNG not seeded"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_RANDOM_POOL_OVERFLOW),
|
||||
"random pool overflow"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG),
|
||||
"request too large for drbg"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_RESEED_ERROR), "reseed error"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_SELFTEST_FAILURE), "selftest failure"},
|
||||
{ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNSUPPORTED_DRBG_TYPE),
|
||||
"unsupported drbg type"},
|
||||
{0, NULL}
|
||||
};
|
||||
|
||||
@@ -33,10 +105,9 @@ static ERR_STRING_DATA RAND_str_reasons[] = {
|
||||
int ERR_load_RAND_strings(void)
|
||||
{
|
||||
#ifndef OPENSSL_NO_ERR
|
||||
|
||||
if (ERR_func_error_string(RAND_str_functs[0].error) == NULL) {
|
||||
ERR_load_strings(0, RAND_str_functs);
|
||||
ERR_load_strings(0, RAND_str_reasons);
|
||||
ERR_load_strings_const(RAND_str_functs);
|
||||
ERR_load_strings_const(RAND_str_reasons);
|
||||
}
|
||||
#endif
|
||||
return 1;
|
||||
|
||||
+219
-31
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
|
||||
* Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
|
||||
*
|
||||
* Licensed under the OpenSSL license (the "License"). You may not use
|
||||
* this file except in compliance with the License. You can obtain a copy
|
||||
@@ -10,37 +10,225 @@
|
||||
#ifndef HEADER_RAND_LCL_H
|
||||
# define HEADER_RAND_LCL_H
|
||||
|
||||
# define ENTROPY_NEEDED 32 /* require 256 bits = 32 bytes of randomness */
|
||||
|
||||
# if !defined(USE_MD5_RAND) && !defined(USE_SHA1_RAND) && !defined(USE_MDC2_RAND) && !defined(USE_MD2_RAND)
|
||||
# define USE_SHA1_RAND
|
||||
# endif
|
||||
|
||||
# include <openssl/aes.h>
|
||||
# include <openssl/evp.h>
|
||||
# define MD_Update(a,b,c) EVP_DigestUpdate(a,b,c)
|
||||
# define MD_Final(a,b) EVP_DigestFinal_ex(a,b,NULL)
|
||||
# if defined(USE_MD5_RAND)
|
||||
# include <openssl/md5.h>
|
||||
# define MD_DIGEST_LENGTH MD5_DIGEST_LENGTH
|
||||
# define MD_Init(a) EVP_DigestInit_ex(a,EVP_md5(), NULL)
|
||||
# define MD(a,b,c) EVP_Digest(a,b,c,NULL,EVP_md5(), NULL)
|
||||
# elif defined(USE_SHA1_RAND)
|
||||
# include <openssl/sha.h>
|
||||
# define MD_DIGEST_LENGTH SHA_DIGEST_LENGTH
|
||||
# define MD_Init(a) EVP_DigestInit_ex(a,EVP_sha1(), NULL)
|
||||
# define MD(a,b,c) EVP_Digest(a,b,c,NULL,EVP_sha1(), NULL)
|
||||
# elif defined(USE_MDC2_RAND)
|
||||
# include <openssl/mdc2.h>
|
||||
# define MD_DIGEST_LENGTH MDC2_DIGEST_LENGTH
|
||||
# define MD_Init(a) EVP_DigestInit_ex(a,EVP_mdc2(), NULL)
|
||||
# define MD(a,b,c) EVP_Digest(a,b,c,NULL,EVP_mdc2(), NULL)
|
||||
# elif defined(USE_MD2_RAND)
|
||||
# include <openssl/md2.h>
|
||||
# define MD_DIGEST_LENGTH MD2_DIGEST_LENGTH
|
||||
# define MD_Init(a) EVP_DigestInit_ex(a,EVP_md2(), NULL)
|
||||
# define MD(a,b,c) EVP_Digest(a,b,c,NULL,EVP_md2(), NULL)
|
||||
# endif
|
||||
# include <openssl/sha.h>
|
||||
# include <openssl/hmac.h>
|
||||
# include <openssl/ec.h>
|
||||
# include "internal/rand.h"
|
||||
|
||||
void rand_hw_xor(unsigned char *buf, size_t num);
|
||||
/* How many times to read the TSC as a randomness source. */
|
||||
# define TSC_READ_COUNT 4
|
||||
|
||||
/* Maximum reseed intervals */
|
||||
# define MAX_RESEED_INTERVAL (1 << 24)
|
||||
# define MAX_RESEED_TIME_INTERVAL (1 << 20) /* approx. 12 days */
|
||||
|
||||
/* Default reseed intervals */
|
||||
# define MASTER_RESEED_INTERVAL (1 << 8)
|
||||
# define SLAVE_RESEED_INTERVAL (1 << 16)
|
||||
# define MASTER_RESEED_TIME_INTERVAL (60*60) /* 1 hour */
|
||||
# define SLAVE_RESEED_TIME_INTERVAL (7*60) /* 7 minutes */
|
||||
|
||||
|
||||
|
||||
/* Max size of additional input and personalization string. */
|
||||
# define DRBG_MAX_LENGTH 4096
|
||||
|
||||
/*
|
||||
* The quotient between max_{entropy,nonce}len and min_{entropy,nonce}len
|
||||
*
|
||||
* The current factor is large enough that the RAND_POOL can store a
|
||||
* random input which has a lousy entropy rate of 0.0625 bits per byte.
|
||||
* This input will be sent through the derivation function which 'compresses'
|
||||
* the low quality input into a high quality output.
|
||||
*/
|
||||
# define DRBG_MINMAX_FACTOR 128
|
||||
|
||||
|
||||
/* DRBG status values */
|
||||
typedef enum drbg_status_e {
|
||||
DRBG_UNINITIALISED,
|
||||
DRBG_READY,
|
||||
DRBG_ERROR
|
||||
} DRBG_STATUS;
|
||||
|
||||
|
||||
/* intantiate */
|
||||
typedef int (*RAND_DRBG_instantiate_fn)(RAND_DRBG *ctx,
|
||||
const unsigned char *ent,
|
||||
size_t entlen,
|
||||
const unsigned char *nonce,
|
||||
size_t noncelen,
|
||||
const unsigned char *pers,
|
||||
size_t perslen);
|
||||
/* reseed */
|
||||
typedef int (*RAND_DRBG_reseed_fn)(RAND_DRBG *ctx,
|
||||
const unsigned char *ent,
|
||||
size_t entlen,
|
||||
const unsigned char *adin,
|
||||
size_t adinlen);
|
||||
/* generat output */
|
||||
typedef int (*RAND_DRBG_generate_fn)(RAND_DRBG *ctx,
|
||||
unsigned char *out,
|
||||
size_t outlen,
|
||||
const unsigned char *adin,
|
||||
size_t adinlen);
|
||||
/* uninstantiate */
|
||||
typedef int (*RAND_DRBG_uninstantiate_fn)(RAND_DRBG *ctx);
|
||||
|
||||
|
||||
/*
|
||||
* The DRBG methods
|
||||
*/
|
||||
|
||||
typedef struct rand_drbg_method_st {
|
||||
RAND_DRBG_instantiate_fn instantiate;
|
||||
RAND_DRBG_reseed_fn reseed;
|
||||
RAND_DRBG_generate_fn generate;
|
||||
RAND_DRBG_uninstantiate_fn uninstantiate;
|
||||
} RAND_DRBG_METHOD;
|
||||
|
||||
|
||||
/*
|
||||
* The state of a DRBG AES-CTR.
|
||||
*/
|
||||
typedef struct rand_drbg_ctr_st {
|
||||
AES_KEY ks;
|
||||
size_t keylen;
|
||||
unsigned char K[32];
|
||||
unsigned char V[16];
|
||||
/* Temp variables used by derivation function */
|
||||
AES_KEY df_ks;
|
||||
AES_KEY df_kxks;
|
||||
/* Temporary block storage used by ctr_df */
|
||||
unsigned char bltmp[16];
|
||||
size_t bltmp_pos;
|
||||
unsigned char KX[48];
|
||||
} RAND_DRBG_CTR;
|
||||
|
||||
|
||||
/*
|
||||
* The state of all types of DRBGs, even though we only have CTR mode
|
||||
* right now.
|
||||
*/
|
||||
struct rand_drbg_st {
|
||||
CRYPTO_RWLOCK *lock;
|
||||
RAND_DRBG *parent;
|
||||
int secure; /* 1: allocated on the secure heap, 0: otherwise */
|
||||
int nid; /* the underlying algorithm */
|
||||
int fork_count;
|
||||
unsigned short flags; /* various external flags */
|
||||
|
||||
/*
|
||||
* The random pool is used by RAND_add()/drbg_add() to attach random
|
||||
* data to the global drbg, such that the rand_drbg_get_entropy() callback
|
||||
* can pull it during instantiation and reseeding. This is necessary to
|
||||
* reconcile the different philosophies of the RAND and the RAND_DRBG
|
||||
* with respect to how randomness is added to the RNG during reseeding
|
||||
* (see PR #4328).
|
||||
*/
|
||||
RAND_POOL *pool;
|
||||
|
||||
/*
|
||||
* The following parameters are setup by the per-type "init" function.
|
||||
*
|
||||
* Currently the only type is CTR_DRBG, its init function is drbg_ctr_init().
|
||||
*
|
||||
* The parameters are closely related to the ones described in
|
||||
* section '10.2.1 CTR_DRBG' of [NIST SP 800-90Ar1], with one
|
||||
* crucial difference: In the NIST standard, all counts are given
|
||||
* in bits, whereas in OpenSSL entropy counts are given in bits
|
||||
* and buffer lengths are given in bytes.
|
||||
*
|
||||
* Since this difference has lead to some confusion in the past,
|
||||
* (see [GitHub Issue #2443], formerly [rt.openssl.org #4055])
|
||||
* the 'len' suffix has been added to all buffer sizes for
|
||||
* clarification.
|
||||
*/
|
||||
|
||||
int strength;
|
||||
size_t max_request;
|
||||
size_t min_entropylen, max_entropylen;
|
||||
size_t min_noncelen, max_noncelen;
|
||||
size_t max_perslen, max_adinlen;
|
||||
|
||||
/* Counts the number of generate requests since the last reseed. */
|
||||
unsigned int generate_counter;
|
||||
/*
|
||||
* Maximum number of generate requests until a reseed is required.
|
||||
* This value is ignored if it is zero.
|
||||
*/
|
||||
unsigned int reseed_interval;
|
||||
/* Stores the time when the last reseeding occurred */
|
||||
time_t reseed_time;
|
||||
/*
|
||||
* Specifies the maximum time interval (in seconds) between reseeds.
|
||||
* This value is ignored if it is zero.
|
||||
*/
|
||||
time_t reseed_time_interval;
|
||||
/*
|
||||
* Counts the number of reseeds since instantiation.
|
||||
* This value is ignored if it is zero.
|
||||
*
|
||||
* This counter is used only for seed propagation from the <master> DRBG
|
||||
* to its two children, the <public> and <private> DRBG. This feature is
|
||||
* very special and its sole purpose is to ensure that any randomness which
|
||||
* is added by RAND_add() or RAND_seed() will have an immediate effect on
|
||||
* the output of RAND_bytes() resp. RAND_priv_bytes().
|
||||
*/
|
||||
unsigned int reseed_counter;
|
||||
|
||||
size_t seedlen;
|
||||
DRBG_STATUS state;
|
||||
|
||||
/* Application data, mainly used in the KATs. */
|
||||
CRYPTO_EX_DATA ex_data;
|
||||
|
||||
/* Implementation specific data (currently only one implementation) */
|
||||
union {
|
||||
RAND_DRBG_CTR ctr;
|
||||
} data;
|
||||
|
||||
/* Implementation specific methods */
|
||||
RAND_DRBG_METHOD *meth;
|
||||
|
||||
/* Callback functions. See comments in rand_lib.c */
|
||||
RAND_DRBG_get_entropy_fn get_entropy;
|
||||
RAND_DRBG_cleanup_entropy_fn cleanup_entropy;
|
||||
RAND_DRBG_get_nonce_fn get_nonce;
|
||||
RAND_DRBG_cleanup_nonce_fn cleanup_nonce;
|
||||
};
|
||||
|
||||
/* The global RAND method, and the global buffer and DRBG instance. */
|
||||
extern RAND_METHOD rand_meth;
|
||||
|
||||
/* How often we've forked (only incremented in child). */
|
||||
extern int rand_fork_count;
|
||||
|
||||
/* Hardware-based seeding functions. */
|
||||
size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool);
|
||||
size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool);
|
||||
|
||||
/* DRBG entropy callbacks. */
|
||||
size_t rand_drbg_get_entropy(RAND_DRBG *drbg,
|
||||
unsigned char **pout,
|
||||
int entropy, size_t min_len, size_t max_len);
|
||||
void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
|
||||
unsigned char *out, size_t outlen);
|
||||
size_t rand_drbg_get_additional_data(unsigned char **pout, size_t max_len);
|
||||
|
||||
/* DRBG helpers */
|
||||
int rand_drbg_restart(RAND_DRBG *drbg,
|
||||
const unsigned char *buffer, size_t len, size_t entropy);
|
||||
|
||||
/* locking api */
|
||||
int rand_drbg_lock(RAND_DRBG *drbg);
|
||||
int rand_drbg_unlock(RAND_DRBG *drbg);
|
||||
int rand_drbg_enable_locking(RAND_DRBG *drbg);
|
||||
|
||||
|
||||
/* initializes the AES-CTR DRBG implementation */
|
||||
int drbg_ctr_init(RAND_DRBG *drbg);
|
||||
|
||||
#endif
|
||||
+726
-48
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
|
||||
* Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
|
||||
*
|
||||
* Licensed under the OpenSSL license (the "License"). You may not use
|
||||
* this file except in compliance with the License. You can obtain a copy
|
||||
@@ -11,39 +11,697 @@
|
||||
#include <time.h>
|
||||
#include "internal/cryptlib.h"
|
||||
#include <openssl/opensslconf.h>
|
||||
#include "internal/rand.h"
|
||||
#include "internal/rand_int.h"
|
||||
#include <openssl/engine.h>
|
||||
#include "internal/thread_once.h"
|
||||
#include "rand_lcl.h"
|
||||
#ifdef OPENSSL_SYS_UNIX
|
||||
# include <sys/types.h>
|
||||
# include <unistd.h>
|
||||
# include <sys/time.h>
|
||||
#endif
|
||||
#include "e_os.h"
|
||||
|
||||
#ifdef OPENSSL_FIPS
|
||||
# include <openssl/fips.h>
|
||||
# include <openssl/fips_rand.h>
|
||||
/* Macro to convert two thirty two bit values into a sixty four bit one */
|
||||
#define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
|
||||
|
||||
/*
|
||||
* Check for the existence and support of POSIX timers. The standard
|
||||
* says that the _POSIX_TIMERS macro will have a positive value if they
|
||||
* are available.
|
||||
*
|
||||
* However, we want an additional constraint: that the timer support does
|
||||
* not require an extra library dependency. Early versions of glibc
|
||||
* require -lrt to be specified on the link line to access the timers,
|
||||
* so this needs to be checked for.
|
||||
*
|
||||
* It is worse because some libraries define __GLIBC__ but don't
|
||||
* support the version testing macro (e.g. uClibc). This means
|
||||
* an extra check is needed.
|
||||
*
|
||||
* The final condition is:
|
||||
* "have posix timers and either not glibc or glibc without -lrt"
|
||||
*
|
||||
* The nested #if sequences are required to avoid using a parameterised
|
||||
* macro that might be undefined.
|
||||
*/
|
||||
#undef OSSL_POSIX_TIMER_OKAY
|
||||
#if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
|
||||
# if defined(__GLIBC__)
|
||||
# if defined(__GLIBC_PREREQ)
|
||||
# if __GLIBC_PREREQ(2, 17)
|
||||
# define OSSL_POSIX_TIMER_OKAY
|
||||
# endif
|
||||
# endif
|
||||
# else
|
||||
# define OSSL_POSIX_TIMER_OKAY
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#ifndef OPENSSL_NO_ENGINE
|
||||
/* non-NULL if default_RAND_meth is ENGINE-provided */
|
||||
static ENGINE *funct_ref = NULL;
|
||||
static CRYPTO_RWLOCK *rand_engine_lock = NULL;
|
||||
static ENGINE *funct_ref;
|
||||
static CRYPTO_RWLOCK *rand_engine_lock;
|
||||
#endif
|
||||
static const RAND_METHOD *default_RAND_meth = NULL;
|
||||
static CRYPTO_RWLOCK *rand_meth_lock = NULL;
|
||||
static CRYPTO_ONCE rand_lock_init = CRYPTO_ONCE_STATIC_INIT;
|
||||
static CRYPTO_RWLOCK *rand_meth_lock;
|
||||
static const RAND_METHOD *default_RAND_meth;
|
||||
static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
|
||||
|
||||
DEFINE_RUN_ONCE_STATIC(do_rand_lock_init)
|
||||
int rand_fork_count;
|
||||
|
||||
#ifdef OPENSSL_RAND_SEED_RDTSC
|
||||
/*
|
||||
* IMPORTANT NOTE: It is not currently possible to use this code
|
||||
* because we are not sure about the amount of randomness it provides.
|
||||
* Some SP900 tests have been run, but there is internal skepticism.
|
||||
* So for now this code is not used.
|
||||
*/
|
||||
# error "RDTSC enabled? Should not be possible!"
|
||||
|
||||
/*
|
||||
* Acquire entropy from high-speed clock
|
||||
*
|
||||
* Since we get some randomness from the low-order bits of the
|
||||
* high-speed clock, it can help.
|
||||
*
|
||||
* Returns the total entropy count, if it exceeds the requested
|
||||
* entropy count. Otherwise, returns an entropy count of 0.
|
||||
*/
|
||||
size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool)
|
||||
{
|
||||
unsigned char c;
|
||||
int i;
|
||||
|
||||
if ((OPENSSL_ia32cap_P[0] & (1 << 4)) != 0) {
|
||||
for (i = 0; i < TSC_READ_COUNT; i++) {
|
||||
c = (unsigned char)(OPENSSL_rdtsc() & 0xFF);
|
||||
RAND_POOL_add(pool, &c, 1, 4);
|
||||
}
|
||||
}
|
||||
return RAND_POOL_entropy_available(pool);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef OPENSSL_RAND_SEED_RDCPU
|
||||
size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len);
|
||||
size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len);
|
||||
|
||||
extern unsigned int OPENSSL_ia32cap_P[];
|
||||
|
||||
/*
|
||||
* Acquire entropy using Intel-specific cpu instructions
|
||||
*
|
||||
* Uses the RDSEED instruction if available, otherwise uses
|
||||
* RDRAND if available.
|
||||
*
|
||||
* For the differences between RDSEED and RDRAND, and why RDSEED
|
||||
* is the preferred choice, see https://goo.gl/oK3KcN
|
||||
*
|
||||
* Returns the total entropy count, if it exceeds the requested
|
||||
* entropy count. Otherwise, returns an entropy count of 0.
|
||||
*/
|
||||
size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool)
|
||||
{
|
||||
size_t bytes_needed;
|
||||
unsigned char *buffer;
|
||||
|
||||
bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/);
|
||||
if (bytes_needed > 0) {
|
||||
buffer = RAND_POOL_add_begin(pool, bytes_needed);
|
||||
|
||||
if (buffer != NULL) {
|
||||
|
||||
/* If RDSEED is available, use that. */
|
||||
if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
|
||||
if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed)
|
||||
== bytes_needed)
|
||||
return RAND_POOL_add_end(pool,
|
||||
bytes_needed,
|
||||
8 * bytes_needed);
|
||||
}
|
||||
|
||||
/* Second choice is RDRAND. */
|
||||
if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
|
||||
if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed)
|
||||
== bytes_needed)
|
||||
return RAND_POOL_add_end(pool,
|
||||
bytes_needed,
|
||||
8 * bytes_needed);
|
||||
}
|
||||
|
||||
return RAND_POOL_add_end(pool, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
return RAND_POOL_entropy_available(pool);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
* Implements the get_entropy() callback (see RAND_DRBG_set_callbacks())
|
||||
*
|
||||
* If the DRBG has a parent, then the required amount of entropy input
|
||||
* is fetched using the parent's RAND_DRBG_generate().
|
||||
*
|
||||
* Otherwise, the entropy is polled from the system entropy sources
|
||||
* using RAND_POOL_acquire_entropy().
|
||||
*
|
||||
* If a random pool has been added to the DRBG using RAND_add(), then
|
||||
* its entropy will be used up first.
|
||||
*/
|
||||
size_t rand_drbg_get_entropy(RAND_DRBG *drbg,
|
||||
unsigned char **pout,
|
||||
int entropy, size_t min_len, size_t max_len)
|
||||
{
|
||||
size_t ret = 0;
|
||||
size_t entropy_available = 0;
|
||||
RAND_POOL *pool = RAND_POOL_new(entropy, min_len, max_len);
|
||||
|
||||
if (pool == NULL)
|
||||
return 0;
|
||||
|
||||
if (drbg->pool) {
|
||||
RAND_POOL_add(pool,
|
||||
RAND_POOL_buffer(drbg->pool),
|
||||
RAND_POOL_length(drbg->pool),
|
||||
RAND_POOL_entropy(drbg->pool));
|
||||
RAND_POOL_free(drbg->pool);
|
||||
drbg->pool = NULL;
|
||||
}
|
||||
|
||||
if (drbg->parent) {
|
||||
size_t bytes_needed = RAND_POOL_bytes_needed(pool, 8);
|
||||
unsigned char *buffer = RAND_POOL_add_begin(pool, bytes_needed);
|
||||
|
||||
if (buffer != NULL) {
|
||||
size_t bytes = 0;
|
||||
|
||||
/*
|
||||
* Get random from parent, include our state as additional input.
|
||||
* Our lock is already held, but we need to lock our parent before
|
||||
* generating bits from it. (Note: taking the lock will be a no-op
|
||||
* if locking if drbg->parent->lock == NULL.)
|
||||
*/
|
||||
rand_drbg_lock(drbg->parent);
|
||||
if (RAND_DRBG_generate(drbg->parent,
|
||||
buffer, bytes_needed,
|
||||
0,
|
||||
(unsigned char *)drbg, sizeof(*drbg)) != 0)
|
||||
bytes = bytes_needed;
|
||||
rand_drbg_unlock(drbg->parent);
|
||||
|
||||
entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes);
|
||||
}
|
||||
|
||||
} else {
|
||||
/* Get entropy by polling system entropy sources. */
|
||||
entropy_available = RAND_POOL_acquire_entropy(pool);
|
||||
}
|
||||
|
||||
if (entropy_available > 0) {
|
||||
ret = RAND_POOL_length(pool);
|
||||
*pout = RAND_POOL_detach(pool);
|
||||
}
|
||||
|
||||
RAND_POOL_free(pool);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/*
|
||||
* Find a suitable source of time. Start with the highest resolution source
|
||||
* and work down to the slower ones. This is added as additional data and
|
||||
* isn't counted as randomness, so any result is acceptable.
|
||||
*
|
||||
* Returns 0 when we weren't able to find any time source
|
||||
*/
|
||||
static uint64_t get_timer_bits(void)
|
||||
{
|
||||
uint64_t res = OPENSSL_rdtsc();
|
||||
|
||||
if (res != 0)
|
||||
return res;
|
||||
#if defined(_WIN32)
|
||||
{
|
||||
LARGE_INTEGER t;
|
||||
FILETIME ft;
|
||||
|
||||
if (QueryPerformanceCounter(&t) != 0)
|
||||
return t.QuadPart;
|
||||
GetSystemTimeAsFileTime(&ft);
|
||||
return TWO32TO64(ft.dwHighDateTime, ft.dwLowDateTime);
|
||||
}
|
||||
#elif defined(__sun) || defined(__hpux)
|
||||
return gethrtime();
|
||||
#elif defined(_AIX)
|
||||
{
|
||||
timebasestruct_t t;
|
||||
|
||||
read_wall_time(&t, TIMEBASE_SZ);
|
||||
return TWO32TO64(t.tb_high, t.tb_low);
|
||||
}
|
||||
#else
|
||||
|
||||
# if defined(OSSL_POSIX_TIMER_OKAY)
|
||||
{
|
||||
struct timespec ts;
|
||||
clockid_t cid;
|
||||
|
||||
# ifdef CLOCK_BOOTTIME
|
||||
cid = CLOCK_BOOTTIME;
|
||||
# elif defined(_POSIX_MONOTONIC_CLOCK)
|
||||
cid = CLOCK_MONOTONIC;
|
||||
# else
|
||||
cid = CLOCK_REALTIME;
|
||||
# endif
|
||||
|
||||
if (clock_gettime(cid, &ts) == 0)
|
||||
return TWO32TO64(ts.tv_sec, ts.tv_nsec);
|
||||
}
|
||||
# endif
|
||||
# if defined(__unix__) \
|
||||
|| (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
|
||||
{
|
||||
struct timeval tv;
|
||||
|
||||
if (gettimeofday(&tv, NULL) == 0)
|
||||
return TWO32TO64(tv.tv_sec, tv.tv_usec);
|
||||
}
|
||||
# endif
|
||||
{
|
||||
time_t t = time(NULL);
|
||||
if (t == (time_t)-1)
|
||||
return 0;
|
||||
return t;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/*
|
||||
* Generate additional data that can be used for the drbg. The data does
|
||||
* not need to contain entropy, but it's useful if it contains at least
|
||||
* some bits that are unpredictable.
|
||||
*
|
||||
* Returns 0 on failure.
|
||||
*
|
||||
* On success it allocates a buffer at |*pout| and returns the length of
|
||||
* the data. The buffer should get freed using OPENSSL_secure_clear_free().
|
||||
*/
|
||||
size_t rand_drbg_get_additional_data(unsigned char **pout, size_t max_len)
|
||||
{
|
||||
RAND_POOL *pool;
|
||||
CRYPTO_THREAD_ID thread_id;
|
||||
size_t len;
|
||||
#ifdef OPENSSL_SYS_UNIX
|
||||
pid_t pid;
|
||||
#elif defined(OPENSSL_SYS_WIN32)
|
||||
DWORD pid;
|
||||
#endif
|
||||
uint64_t tbits;
|
||||
|
||||
pool = RAND_POOL_new(0, 0, max_len);
|
||||
if (pool == NULL)
|
||||
return 0;
|
||||
|
||||
#ifdef OPENSSL_SYS_UNIX
|
||||
pid = getpid();
|
||||
RAND_POOL_add(pool, (unsigned char *)&pid, sizeof(pid), 0);
|
||||
#elif defined(OPENSSL_SYS_WIN32)
|
||||
pid = GetCurrentProcessId();
|
||||
RAND_POOL_add(pool, (unsigned char *)&pid, sizeof(pid), 0);
|
||||
#endif
|
||||
|
||||
thread_id = CRYPTO_THREAD_get_current_id();
|
||||
if (thread_id != 0)
|
||||
RAND_POOL_add(pool, (unsigned char *)&thread_id, sizeof(thread_id), 0);
|
||||
|
||||
tbits = get_timer_bits();
|
||||
if (tbits != 0)
|
||||
RAND_POOL_add(pool, (unsigned char *)&tbits, sizeof(tbits), 0);
|
||||
|
||||
/* TODO: Use RDSEED? */
|
||||
|
||||
len = RAND_POOL_length(pool);
|
||||
if (len != 0)
|
||||
*pout = RAND_POOL_detach(pool);
|
||||
RAND_POOL_free(pool);
|
||||
|
||||
return len;
|
||||
}
|
||||
|
||||
/*
|
||||
* Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
|
||||
*
|
||||
*/
|
||||
void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
|
||||
unsigned char *out, size_t outlen)
|
||||
{
|
||||
OPENSSL_secure_clear_free(out, outlen);
|
||||
}
|
||||
|
||||
void rand_fork()
|
||||
{
|
||||
rand_fork_count++;
|
||||
}
|
||||
|
||||
DEFINE_RUN_ONCE_STATIC(do_rand_init)
|
||||
{
|
||||
int ret = 1;
|
||||
|
||||
#ifndef OPENSSL_NO_ENGINE
|
||||
rand_engine_lock = CRYPTO_THREAD_lock_new();
|
||||
ret &= rand_engine_lock != NULL;
|
||||
#endif
|
||||
rand_meth_lock = CRYPTO_THREAD_lock_new();
|
||||
ret &= rand_meth_lock != NULL;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
void rand_cleanup_int(void)
|
||||
{
|
||||
const RAND_METHOD *meth = default_RAND_meth;
|
||||
|
||||
if (meth != NULL && meth->cleanup != NULL)
|
||||
meth->cleanup();
|
||||
RAND_set_rand_method(NULL);
|
||||
#ifndef OPENSSL_NO_ENGINE
|
||||
CRYPTO_THREAD_lock_free(rand_engine_lock);
|
||||
#endif
|
||||
CRYPTO_THREAD_lock_free(rand_meth_lock);
|
||||
}
|
||||
|
||||
/*
|
||||
* RAND_poll() reseeds the default RNG using random input
|
||||
*
|
||||
* The random input is obtained from polling various entropy
|
||||
* sources which depend on the operating system and are
|
||||
* configurable via the --with-rand-seed configure option.
|
||||
*/
|
||||
int RAND_poll(void)
|
||||
{
|
||||
int ret = 0;
|
||||
|
||||
RAND_POOL *pool = NULL;
|
||||
|
||||
const RAND_METHOD *meth = RAND_get_rand_method();
|
||||
|
||||
if (meth == RAND_OpenSSL()) {
|
||||
/* fill random pool and seed the master DRBG */
|
||||
RAND_DRBG *drbg = RAND_DRBG_get0_master();
|
||||
|
||||
if (drbg == NULL)
|
||||
return 0;
|
||||
|
||||
rand_drbg_lock(drbg);
|
||||
ret = rand_drbg_restart(drbg, NULL, 0, 0);
|
||||
rand_drbg_unlock(drbg);
|
||||
|
||||
return ret;
|
||||
|
||||
} else {
|
||||
/* fill random pool and seed the current legacy RNG */
|
||||
pool = RAND_POOL_new(RAND_DRBG_STRENGTH,
|
||||
RAND_DRBG_STRENGTH / 8,
|
||||
DRBG_MINMAX_FACTOR * (RAND_DRBG_STRENGTH / 8));
|
||||
if (pool == NULL)
|
||||
return 0;
|
||||
|
||||
if (RAND_POOL_acquire_entropy(pool) == 0)
|
||||
goto err;
|
||||
|
||||
if (meth->add == NULL
|
||||
|| meth->add(RAND_POOL_buffer(pool),
|
||||
RAND_POOL_length(pool),
|
||||
(RAND_POOL_entropy(pool) / 8.0)) == 0)
|
||||
goto err;
|
||||
|
||||
ret = 1;
|
||||
}
|
||||
|
||||
err:
|
||||
RAND_POOL_free(pool);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/*
|
||||
* The 'random pool' acts as a dumb container for collecting random
|
||||
* input from various entropy sources. The pool has no knowledge about
|
||||
* whether its randomness is fed into a legacy RAND_METHOD via RAND_add()
|
||||
* or into a new style RAND_DRBG. It is the callers duty to 1) initialize the
|
||||
* random pool, 2) pass it to the polling callbacks, 3) seed the RNG, and
|
||||
* 4) cleanup the random pool again.
|
||||
*
|
||||
* The random pool contains no locking mechanism because its scope and
|
||||
* lifetime is intended to be restricted to a single stack frame.
|
||||
*/
|
||||
struct rand_pool_st {
|
||||
unsigned char *buffer; /* points to the beginning of the random pool */
|
||||
size_t len; /* current number of random bytes contained in the pool */
|
||||
|
||||
size_t min_len; /* minimum number of random bytes requested */
|
||||
size_t max_len; /* maximum number of random bytes (allocated buffer size) */
|
||||
size_t entropy; /* current entropy count in bits */
|
||||
size_t requested_entropy; /* requested entropy count in bits */
|
||||
};
|
||||
|
||||
/*
|
||||
* Allocate memory and initialize a new random pool
|
||||
*/
|
||||
|
||||
RAND_POOL *RAND_POOL_new(int entropy, size_t min_len, size_t max_len)
|
||||
{
|
||||
RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
|
||||
|
||||
if (pool == NULL) {
|
||||
RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
|
||||
goto err;
|
||||
}
|
||||
|
||||
pool->min_len = min_len;
|
||||
pool->max_len = max_len;
|
||||
|
||||
pool->buffer = OPENSSL_secure_zalloc(pool->max_len);
|
||||
if (pool->buffer == NULL) {
|
||||
RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
|
||||
goto err;
|
||||
}
|
||||
|
||||
pool->requested_entropy = entropy;
|
||||
|
||||
return pool;
|
||||
|
||||
err:
|
||||
OPENSSL_free(pool);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
* Free |pool|, securely erasing its buffer.
|
||||
*/
|
||||
void RAND_POOL_free(RAND_POOL *pool)
|
||||
{
|
||||
if (pool == NULL)
|
||||
return;
|
||||
|
||||
OPENSSL_secure_clear_free(pool->buffer, pool->max_len);
|
||||
OPENSSL_free(pool);
|
||||
}
|
||||
|
||||
/*
|
||||
* Return the |pool|'s buffer to the caller (readonly).
|
||||
*/
|
||||
const unsigned char *RAND_POOL_buffer(RAND_POOL *pool)
|
||||
{
|
||||
return pool->buffer;
|
||||
}
|
||||
|
||||
/*
|
||||
* Return the |pool|'s entropy to the caller.
|
||||
*/
|
||||
size_t RAND_POOL_entropy(RAND_POOL *pool)
|
||||
{
|
||||
return pool->entropy;
|
||||
}
|
||||
|
||||
/*
|
||||
* Return the |pool|'s buffer length to the caller.
|
||||
*/
|
||||
size_t RAND_POOL_length(RAND_POOL *pool)
|
||||
{
|
||||
return pool->len;
|
||||
}
|
||||
|
||||
/*
|
||||
* Detach the |pool| buffer and return it to the caller.
|
||||
* It's the responsibility of the caller to free the buffer
|
||||
* using OPENSSL_secure_clear_free().
|
||||
*/
|
||||
unsigned char *RAND_POOL_detach(RAND_POOL *pool)
|
||||
{
|
||||
unsigned char *ret = pool->buffer;
|
||||
pool->buffer = NULL;
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* If every byte of the input contains |entropy_per_bytes| bits of entropy,
|
||||
* how many bytes does one need to obtain at least |bits| bits of entropy?
|
||||
*/
|
||||
#define ENTROPY_TO_BYTES(bits, entropy_per_bytes) \
|
||||
(((bits) + ((entropy_per_bytes) - 1))/(entropy_per_bytes))
|
||||
|
||||
|
||||
/*
|
||||
* Checks whether the |pool|'s entropy is available to the caller.
|
||||
* This is the case when entropy count and buffer length are high enough.
|
||||
* Returns
|
||||
*
|
||||
* |entropy| if the entropy count and buffer size is large enough
|
||||
* 0 otherwise
|
||||
*/
|
||||
size_t RAND_POOL_entropy_available(RAND_POOL *pool)
|
||||
{
|
||||
if (pool->entropy < pool->requested_entropy)
|
||||
return 0;
|
||||
|
||||
if (pool->len < pool->min_len)
|
||||
return 0;
|
||||
|
||||
return pool->entropy;
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns the (remaining) amount of entropy needed to fill
|
||||
* the random pool.
|
||||
*/
|
||||
|
||||
size_t RAND_POOL_entropy_needed(RAND_POOL *pool)
|
||||
{
|
||||
if (pool->entropy < pool->requested_entropy)
|
||||
return pool->requested_entropy - pool->entropy;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns the number of bytes needed to fill the pool, assuming
|
||||
* the input has 'entropy_per_byte' entropy bits per byte.
|
||||
* In case of an error, 0 is returned.
|
||||
*/
|
||||
|
||||
size_t RAND_POOL_bytes_needed(RAND_POOL *pool, unsigned int entropy_per_byte)
|
||||
{
|
||||
size_t bytes_needed;
|
||||
size_t entropy_needed = RAND_POOL_entropy_needed(pool);
|
||||
|
||||
if (entropy_per_byte < 1 || entropy_per_byte > 8) {
|
||||
RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
|
||||
return 0;
|
||||
}
|
||||
|
||||
bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_per_byte);
|
||||
|
||||
if (bytes_needed > pool->max_len - pool->len) {
|
||||
/* not enough space left */
|
||||
RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (pool->len < pool->min_len &&
|
||||
bytes_needed < pool->min_len - pool->len)
|
||||
/* to meet the min_len requirement */
|
||||
bytes_needed = pool->min_len - pool->len;
|
||||
|
||||
return bytes_needed;
|
||||
}
|
||||
|
||||
/* Returns the remaining number of bytes available */
|
||||
size_t RAND_POOL_bytes_remaining(RAND_POOL *pool)
|
||||
{
|
||||
return pool->max_len - pool->len;
|
||||
}
|
||||
|
||||
/*
|
||||
* Add random bytes to the random pool.
|
||||
*
|
||||
* It is expected that the |buffer| contains |len| bytes of
|
||||
* random input which contains at least |entropy| bits of
|
||||
* randomness.
|
||||
*
|
||||
* Return available amount of entropy after this operation.
|
||||
* (see RAND_POOL_entropy_available(pool))
|
||||
*/
|
||||
size_t RAND_POOL_add(RAND_POOL *pool,
|
||||
const unsigned char *buffer, size_t len, size_t entropy)
|
||||
{
|
||||
if (len > pool->max_len - pool->len) {
|
||||
RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (len > 0) {
|
||||
memcpy(pool->buffer + pool->len, buffer, len);
|
||||
pool->len += len;
|
||||
pool->entropy += entropy;
|
||||
}
|
||||
|
||||
return RAND_POOL_entropy_available(pool);
|
||||
}
|
||||
|
||||
/*
|
||||
* Start to add random bytes to the random pool in-place.
|
||||
*
|
||||
* Reserves the next |len| bytes for adding random bytes in-place
|
||||
* and returns a pointer to the buffer.
|
||||
* The caller is allowed to copy up to |len| bytes into the buffer.
|
||||
* If |len| == 0 this is considered a no-op and a NULL pointer
|
||||
* is returned without producing an error message.
|
||||
*
|
||||
* After updating the buffer, RAND_POOL_add_end() needs to be called
|
||||
* to finish the udpate operation (see next comment).
|
||||
*/
|
||||
unsigned char *RAND_POOL_add_begin(RAND_POOL *pool, size_t len)
|
||||
{
|
||||
if (len == 0)
|
||||
return NULL;
|
||||
|
||||
if (len > pool->max_len - pool->len) {
|
||||
RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return pool->buffer + pool->len;
|
||||
}
|
||||
|
||||
/*
|
||||
* Finish to add random bytes to the random pool in-place.
|
||||
*
|
||||
* Finishes an in-place update of the random pool started by
|
||||
* RAND_POOL_add_begin() (see previous comment).
|
||||
* It is expected that |len| bytes of random input have been added
|
||||
* to the buffer which contain at least |entropy| bits of randomness.
|
||||
* It is allowed to add less bytes than originally reserved.
|
||||
*/
|
||||
size_t RAND_POOL_add_end(RAND_POOL *pool, size_t len, size_t entropy)
|
||||
{
|
||||
if (len > pool->max_len - pool->len) {
|
||||
RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (len > 0) {
|
||||
pool->len += len;
|
||||
pool->entropy += entropy;
|
||||
}
|
||||
|
||||
return RAND_POOL_entropy_available(pool);
|
||||
}
|
||||
|
||||
int RAND_set_rand_method(const RAND_METHOD *meth)
|
||||
{
|
||||
if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
|
||||
if (!RUN_ONCE(&rand_init, do_rand_init))
|
||||
return 0;
|
||||
|
||||
CRYPTO_THREAD_write_lock(rand_meth_lock);
|
||||
@@ -60,25 +718,26 @@ const RAND_METHOD *RAND_get_rand_method(void)
|
||||
{
|
||||
const RAND_METHOD *tmp_meth = NULL;
|
||||
|
||||
if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
|
||||
if (!RUN_ONCE(&rand_init, do_rand_init))
|
||||
return NULL;
|
||||
|
||||
CRYPTO_THREAD_write_lock(rand_meth_lock);
|
||||
if (!default_RAND_meth) {
|
||||
if (default_RAND_meth == NULL) {
|
||||
#ifndef OPENSSL_NO_ENGINE
|
||||
ENGINE *e = ENGINE_get_default_RAND();
|
||||
if (e) {
|
||||
default_RAND_meth = ENGINE_get_RAND(e);
|
||||
if (default_RAND_meth == NULL) {
|
||||
ENGINE_finish(e);
|
||||
e = NULL;
|
||||
}
|
||||
}
|
||||
if (e)
|
||||
ENGINE *e;
|
||||
|
||||
/* If we have an engine that can do RAND, use it. */
|
||||
if ((e = ENGINE_get_default_RAND()) != NULL
|
||||
&& (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
|
||||
funct_ref = e;
|
||||
else
|
||||
default_RAND_meth = tmp_meth;
|
||||
} else {
|
||||
ENGINE_finish(e);
|
||||
default_RAND_meth = &rand_meth;
|
||||
}
|
||||
#else
|
||||
default_RAND_meth = &rand_meth;
|
||||
#endif
|
||||
default_RAND_meth = RAND_OpenSSL();
|
||||
}
|
||||
tmp_meth = default_RAND_meth;
|
||||
CRYPTO_THREAD_unlock(rand_meth_lock);
|
||||
@@ -90,10 +749,10 @@ int RAND_set_rand_engine(ENGINE *engine)
|
||||
{
|
||||
const RAND_METHOD *tmp_meth = NULL;
|
||||
|
||||
if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init))
|
||||
if (!RUN_ONCE(&rand_init, do_rand_init))
|
||||
return 0;
|
||||
|
||||
if (engine) {
|
||||
if (engine != NULL) {
|
||||
if (!ENGINE_init(engine))
|
||||
return 0;
|
||||
tmp_meth = ENGINE_get_RAND(engine);
|
||||
@@ -111,54 +770,73 @@ int RAND_set_rand_engine(ENGINE *engine)
|
||||
}
|
||||
#endif
|
||||
|
||||
void rand_cleanup_int(void)
|
||||
{
|
||||
const RAND_METHOD *meth = default_RAND_meth;
|
||||
if (meth && meth->cleanup)
|
||||
meth->cleanup();
|
||||
RAND_set_rand_method(NULL);
|
||||
CRYPTO_THREAD_lock_free(rand_meth_lock);
|
||||
#ifndef OPENSSL_NO_ENGINE
|
||||
CRYPTO_THREAD_lock_free(rand_engine_lock);
|
||||
#endif
|
||||
}
|
||||
|
||||
void RAND_seed(const void *buf, int num)
|
||||
{
|
||||
const RAND_METHOD *meth = RAND_get_rand_method();
|
||||
if (meth && meth->seed)
|
||||
|
||||
if (meth->seed != NULL)
|
||||
meth->seed(buf, num);
|
||||
}
|
||||
|
||||
void RAND_add(const void *buf, int num, double entropy)
|
||||
void RAND_add(const void *buf, int num, double randomness)
|
||||
{
|
||||
const RAND_METHOD *meth = RAND_get_rand_method();
|
||||
if (meth && meth->add)
|
||||
meth->add(buf, num, entropy);
|
||||
|
||||
if (meth->add != NULL)
|
||||
meth->add(buf, num, randomness);
|
||||
}
|
||||
|
||||
/*
|
||||
* This function is not part of RAND_METHOD, so if we're not using
|
||||
* the default method, then just call RAND_bytes(). Otherwise make
|
||||
* sure we're instantiated and use the private DRBG.
|
||||
*/
|
||||
int RAND_priv_bytes(unsigned char *buf, int num)
|
||||
{
|
||||
const RAND_METHOD *meth = RAND_get_rand_method();
|
||||
RAND_DRBG *drbg;
|
||||
int ret;
|
||||
|
||||
if (meth != RAND_OpenSSL())
|
||||
return RAND_bytes(buf, num);
|
||||
|
||||
drbg = RAND_DRBG_get0_private();
|
||||
if (drbg == NULL)
|
||||
return 0;
|
||||
|
||||
/* We have to lock the DRBG before generating bits from it. */
|
||||
rand_drbg_lock(drbg);
|
||||
ret = RAND_DRBG_bytes(drbg, buf, num);
|
||||
rand_drbg_unlock(drbg);
|
||||
return ret;
|
||||
}
|
||||
|
||||
int RAND_bytes(unsigned char *buf, int num)
|
||||
{
|
||||
const RAND_METHOD *meth = RAND_get_rand_method();
|
||||
if (meth && meth->bytes)
|
||||
|
||||
if (meth->bytes != NULL)
|
||||
return meth->bytes(buf, num);
|
||||
return (-1);
|
||||
RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
|
||||
return -1;
|
||||
}
|
||||
|
||||
#if OPENSSL_API_COMPAT < 0x10100000L
|
||||
int RAND_pseudo_bytes(unsigned char *buf, int num)
|
||||
{
|
||||
const RAND_METHOD *meth = RAND_get_rand_method();
|
||||
if (meth && meth->pseudorand)
|
||||
|
||||
if (meth->pseudorand != NULL)
|
||||
return meth->pseudorand(buf, num);
|
||||
return (-1);
|
||||
return -1;
|
||||
}
|
||||
#endif
|
||||
|
||||
int RAND_status(void)
|
||||
{
|
||||
const RAND_METHOD *meth = RAND_get_rand_method();
|
||||
if (meth && meth->status)
|
||||
|
||||
if (meth->status != NULL)
|
||||
return meth->status();
|
||||
return 0;
|
||||
}
|
||||
+171
-239
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
|
||||
* Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
|
||||
*
|
||||
* Licensed under the OpenSSL license (the "License"). You may not use
|
||||
* this file except in compliance with the License. You can obtain a copy
|
||||
@@ -7,91 +7,81 @@
|
||||
* https://www.openssl.org/source/license.html
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#define USE_SOCKETS
|
||||
#include "e_os.h"
|
||||
#include <stdio.h>
|
||||
#include "internal/cryptlib.h"
|
||||
#include <openssl/rand.h>
|
||||
#include "rand_lcl.h"
|
||||
#include <stdio.h>
|
||||
|
||||
#if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI))
|
||||
#if (defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)) && \
|
||||
!defined(OPENSSL_RAND_SEED_NONE)
|
||||
# error "UEFI and VXWorks only support seeding NONE"
|
||||
#endif
|
||||
|
||||
# include <sys/types.h>
|
||||
# include <sys/time.h>
|
||||
# include <sys/times.h>
|
||||
# include <sys/stat.h>
|
||||
# include <fcntl.h>
|
||||
# include <unistd.h>
|
||||
# include <time.h>
|
||||
# if defined(OPENSSL_SYS_LINUX) /* should actually be available virtually
|
||||
* everywhere */
|
||||
# include <poll.h>
|
||||
# endif
|
||||
# include <limits.h>
|
||||
# ifndef FD_SETSIZE
|
||||
# define FD_SETSIZE (8*sizeof(fd_set))
|
||||
# endif
|
||||
#if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \
|
||||
|| defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \
|
||||
|| defined(OPENSSL_SYS_UEFI))
|
||||
|
||||
# if defined(OPENSSL_SYS_VOS)
|
||||
|
||||
# ifndef OPENSSL_RAND_SEED_OS
|
||||
# error "Unsupported seeding method configured; must be os"
|
||||
# endif
|
||||
|
||||
# if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32)
|
||||
# error "Unsupported HP-PA and IA32 at the same time."
|
||||
# endif
|
||||
# if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32)
|
||||
# error "Must have one of HP-PA or IA32"
|
||||
# endif
|
||||
|
||||
/*
|
||||
* The following algorithm repeatedly samples the real-time clock (RTC) to
|
||||
* generate a sequence of unpredictable data. The algorithm relies upon the
|
||||
* uneven execution speed of the code (due to factors such as cache misses,
|
||||
* interrupts, bus activity, and scheduling) and upon the rather large
|
||||
* relative difference between the speed of the clock and the rate at which
|
||||
* it can be read.
|
||||
* it can be read. If it is ported to an environment where execution speed
|
||||
* is more constant or where the RTC ticks at a much slower rate, or the
|
||||
* clock can be read with fewer instructions, it is likely that the results
|
||||
* would be far more predictable. This should only be used for legacy
|
||||
* platforms.
|
||||
*
|
||||
* If this code is ported to an environment where execution speed is more
|
||||
* constant or where the RTC ticks at a much slower rate, or the clock can be
|
||||
* read with fewer instructions, it is likely that the results would be far
|
||||
* more predictable.
|
||||
*
|
||||
* As a precaution, we generate 4 times the minimum required amount of seed
|
||||
* data.
|
||||
* As a precaution, we assume only 2 bits of entropy per byte.
|
||||
*/
|
||||
|
||||
int RAND_poll(void)
|
||||
size_t RAND_POOL_acquire_entropy(RAND_POOL *pool)
|
||||
{
|
||||
short int code;
|
||||
gid_t curr_gid;
|
||||
pid_t curr_pid;
|
||||
uid_t curr_uid;
|
||||
int i, k;
|
||||
size_t bytes_needed;
|
||||
struct timespec ts;
|
||||
unsigned char v;
|
||||
|
||||
# ifdef OPENSSL_SYS_VOS_HPPA
|
||||
long duration;
|
||||
extern void s$sleep(long *_duration, short int *_code);
|
||||
# else
|
||||
# ifdef OPENSSL_SYS_VOS_IA32
|
||||
long long duration;
|
||||
extern void s$sleep2(long long *_duration, short int *_code);
|
||||
# else
|
||||
# error "Unsupported Platform."
|
||||
# endif /* OPENSSL_SYS_VOS_IA32 */
|
||||
# endif /* OPENSSL_SYS_VOS_HPPA */
|
||||
# endif
|
||||
|
||||
/*
|
||||
* Seed with the gid, pid, and uid, to ensure *some* variation between
|
||||
* different processes.
|
||||
*/
|
||||
|
||||
curr_gid = getgid();
|
||||
RAND_add(&curr_gid, sizeof(curr_gid), 1);
|
||||
curr_gid = 0;
|
||||
|
||||
RAND_POOL_add(pool, &curr_gid, sizeof(curr_gid), 0);
|
||||
curr_pid = getpid();
|
||||
RAND_add(&curr_pid, sizeof(curr_pid), 1);
|
||||
curr_pid = 0;
|
||||
|
||||
RAND_POOL_add(pool, &curr_pid, sizeof(curr_pid), 0);
|
||||
curr_uid = getuid();
|
||||
RAND_add(&curr_uid, sizeof(curr_uid), 1);
|
||||
curr_uid = 0;
|
||||
RAND_POOL_add(pool, &curr_uid, sizeof(curr_uid), 0);
|
||||
|
||||
for (i = 0; i < (ENTROPY_NEEDED * 4); i++) {
|
||||
bytes_needed = RAND_POOL_bytes_needed(pool, 2 /*entropy_per_byte*/);
|
||||
|
||||
for (i = 0; i < bytes_needed; i++) {
|
||||
/*
|
||||
* burn some cpu; hope for interrupts, cache collisions, bus
|
||||
* interference, etc.
|
||||
@@ -104,221 +94,163 @@ int RAND_poll(void)
|
||||
duration = 1;
|
||||
s$sleep(&duration, &code);
|
||||
# else
|
||||
# ifdef OPENSSL_SYS_VOS_IA32
|
||||
/* sleep for 1/65536 of a second (15 us). */
|
||||
duration = 1;
|
||||
s$sleep2(&duration, &code);
|
||||
# endif /* OPENSSL_SYS_VOS_IA32 */
|
||||
# endif /* OPENSSL_SYS_VOS_HPPA */
|
||||
# endif
|
||||
|
||||
/* get wall clock time. */
|
||||
/* Get wall clock time, take 8 bits. */
|
||||
clock_gettime(CLOCK_REALTIME, &ts);
|
||||
|
||||
/* take 8 bits */
|
||||
v = (unsigned char)(ts.tv_nsec % 256);
|
||||
RAND_add(&v, sizeof(v), 1);
|
||||
v = 0;
|
||||
v = (unsigned char)(ts.tv_nsec & 0xFF);
|
||||
RAND_POOL_add(pool, arg, &v, sizeof(v) , 2);
|
||||
}
|
||||
return 1;
|
||||
return RAND_POOL_entropy_available(pool);
|
||||
}
|
||||
# elif defined __OpenBSD__
|
||||
int RAND_poll(void)
|
||||
{
|
||||
u_int32_t rnd = 0, i;
|
||||
unsigned char buf[ENTROPY_NEEDED];
|
||||
|
||||
for (i = 0; i < sizeof(buf); i++) {
|
||||
if (i % 4 == 0)
|
||||
rnd = arc4random();
|
||||
buf[i] = rnd;
|
||||
rnd >>= 8;
|
||||
# else
|
||||
|
||||
# if defined(OPENSSL_RAND_SEED_EGD) && \
|
||||
(defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD))
|
||||
# error "Seeding uses EGD but EGD is turned off or no device given"
|
||||
# endif
|
||||
|
||||
# if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM)
|
||||
# error "Seeding uses urandom but DEVRANDOM is not configured"
|
||||
# endif
|
||||
|
||||
# if defined(OPENSSL_RAND_SEED_OS)
|
||||
# if !defined(DEVRANDOM)
|
||||
# error "OS seeding requires DEVRANDOM to be configured"
|
||||
# endif
|
||||
# define OPENSSL_RAND_SEED_DEVRANDOM
|
||||
# if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
|
||||
# if __GLIBC_PREREQ(2, 25)
|
||||
# define OPENSSL_RAND_SEED_GETRANDOM
|
||||
# endif
|
||||
# endif
|
||||
# endif
|
||||
|
||||
# ifdef OPENSSL_RAND_SEED_GETRANDOM
|
||||
# include <sys/random.h>
|
||||
# endif
|
||||
|
||||
# if defined(OPENSSL_RAND_SEED_LIBRANDOM)
|
||||
# error "librandom not (yet) supported"
|
||||
# endif
|
||||
|
||||
/*
|
||||
* Try the various seeding methods in turn, exit when successful.
|
||||
*
|
||||
* TODO(DRBG): If more than one entropy source is available, is it
|
||||
* preferable to stop as soon as enough entropy has been collected
|
||||
* (as favored by @rsalz) or should one rather be defensive and add
|
||||
* more entropy than requested and/or from different sources?
|
||||
*
|
||||
* Currently, the user can select multiple entropy sources in the
|
||||
* configure step, yet in practice only the first available source
|
||||
* will be used. A more flexible solution has been requested, but
|
||||
* currently it is not clear how this can be achieved without
|
||||
* overengineering the problem. There are many parameters which
|
||||
* could be taken into account when selecting the order and amount
|
||||
* of input from the different entropy sources (trust, quality,
|
||||
* possibility of blocking).
|
||||
*/
|
||||
size_t RAND_POOL_acquire_entropy(RAND_POOL *pool)
|
||||
{
|
||||
# ifdef OPENSSL_RAND_SEED_NONE
|
||||
return RAND_POOL_entropy_available(pool);
|
||||
# else
|
||||
size_t bytes_needed;
|
||||
size_t entropy_available = 0;
|
||||
unsigned char *buffer;
|
||||
|
||||
# ifdef OPENSSL_RAND_SEED_GETRANDOM
|
||||
bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/);
|
||||
buffer = RAND_POOL_add_begin(pool, bytes_needed);
|
||||
if (buffer != NULL) {
|
||||
size_t bytes = 0;
|
||||
|
||||
if (getrandom(buffer, bytes_needed, 0) == (int)bytes_needed)
|
||||
bytes = bytes_needed;
|
||||
|
||||
entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes);
|
||||
}
|
||||
RAND_add(buf, sizeof(buf), ENTROPY_NEEDED);
|
||||
OPENSSL_cleanse(buf, sizeof(buf));
|
||||
|
||||
return 1;
|
||||
}
|
||||
# else /* !defined(__OpenBSD__) */
|
||||
int RAND_poll(void)
|
||||
{
|
||||
unsigned long l;
|
||||
pid_t curr_pid = getpid();
|
||||
# if defined(DEVRANDOM) || (!defined(OPENSS_NO_EGD) && defined(DEVRANDOM_EGD))
|
||||
unsigned char tmpbuf[ENTROPY_NEEDED];
|
||||
int n = 0;
|
||||
# endif
|
||||
# ifdef DEVRANDOM
|
||||
static const char *randomfiles[] = { DEVRANDOM };
|
||||
struct stat randomstats[OSSL_NELEM(randomfiles)];
|
||||
int fd;
|
||||
unsigned int i;
|
||||
# endif
|
||||
# if !defined(OPENSSL_NO_EGD) && defined(DEVRANDOM_EGD)
|
||||
static const char *egdsockets[] = { DEVRANDOM_EGD, NULL };
|
||||
const char **egdsocket = NULL;
|
||||
# endif
|
||||
|
||||
# ifdef DEVRANDOM
|
||||
memset(randomstats, 0, sizeof(randomstats));
|
||||
/*
|
||||
* Use a random entropy pool device. Linux, FreeBSD and OpenBSD have
|
||||
* this. Use /dev/urandom if you can as /dev/random may block if it runs
|
||||
* out of random entries.
|
||||
*/
|
||||
|
||||
for (i = 0; (i < OSSL_NELEM(randomfiles)) && (n < ENTROPY_NEEDED); i++) {
|
||||
if ((fd = open(randomfiles[i], O_RDONLY
|
||||
# ifdef O_NONBLOCK
|
||||
| O_NONBLOCK
|
||||
if (entropy_available > 0)
|
||||
return entropy_available;
|
||||
# endif
|
||||
# ifdef O_BINARY
|
||||
| O_BINARY
|
||||
# endif
|
||||
# ifdef O_NOCTTY /* If it happens to be a TTY (god forbid), do
|
||||
* not make it our controlling tty */
|
||||
| O_NOCTTY
|
||||
# endif
|
||||
)) >= 0) {
|
||||
int usec = 10 * 1000; /* spend 10ms on each file */
|
||||
int r;
|
||||
unsigned int j;
|
||||
struct stat *st = &randomstats[i];
|
||||
|
||||
/*
|
||||
* Avoid using same input... Used to be O_NOFOLLOW above, but
|
||||
* it's not universally appropriate...
|
||||
*/
|
||||
if (fstat(fd, st) != 0) {
|
||||
close(fd);
|
||||
continue;
|
||||
}
|
||||
for (j = 0; j < i; j++) {
|
||||
if (randomstats[j].st_ino == st->st_ino &&
|
||||
randomstats[j].st_dev == st->st_dev)
|
||||
break;
|
||||
}
|
||||
if (j < i) {
|
||||
close(fd);
|
||||
# if defined(OPENSSL_RAND_SEED_LIBRANDOM)
|
||||
{
|
||||
/* Not yet implemented. */
|
||||
}
|
||||
# endif
|
||||
|
||||
# ifdef OPENSSL_RAND_SEED_DEVRANDOM
|
||||
bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/);
|
||||
if (bytes_needed > 0) {
|
||||
static const char *paths[] = { DEVRANDOM, NULL };
|
||||
FILE *fp;
|
||||
int i;
|
||||
|
||||
for (i = 0; paths[i] != NULL; i++) {
|
||||
if ((fp = fopen(paths[i], "rb")) == NULL)
|
||||
continue;
|
||||
setbuf(fp, NULL);
|
||||
buffer = RAND_POOL_add_begin(pool, bytes_needed);
|
||||
if (buffer != NULL) {
|
||||
size_t bytes = 0;
|
||||
if (fread(buffer, 1, bytes_needed, fp) == bytes_needed)
|
||||
bytes = bytes_needed;
|
||||
|
||||
entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes);
|
||||
}
|
||||
fclose(fp);
|
||||
if (entropy_available > 0)
|
||||
return entropy_available;
|
||||
|
||||
do {
|
||||
int try_read = 0;
|
||||
|
||||
# if defined(OPENSSL_SYS_LINUX)
|
||||
/* use poll() */
|
||||
struct pollfd pset;
|
||||
|
||||
pset.fd = fd;
|
||||
pset.events = POLLIN;
|
||||
pset.revents = 0;
|
||||
|
||||
if (poll(&pset, 1, usec / 1000) < 0)
|
||||
usec = 0;
|
||||
else
|
||||
try_read = (pset.revents & POLLIN) != 0;
|
||||
|
||||
# else
|
||||
/* use select() */
|
||||
fd_set fset;
|
||||
struct timeval t;
|
||||
|
||||
t.tv_sec = 0;
|
||||
t.tv_usec = usec;
|
||||
|
||||
if (FD_SETSIZE > 0 && (unsigned)fd >= FD_SETSIZE) {
|
||||
/*
|
||||
* can't use select, so just try to read once anyway
|
||||
*/
|
||||
try_read = 1;
|
||||
} else {
|
||||
FD_ZERO(&fset);
|
||||
FD_SET(fd, &fset);
|
||||
|
||||
if (select(fd + 1, &fset, NULL, NULL, &t) >= 0) {
|
||||
usec = t.tv_usec;
|
||||
if (FD_ISSET(fd, &fset))
|
||||
try_read = 1;
|
||||
} else
|
||||
usec = 0;
|
||||
}
|
||||
# endif
|
||||
|
||||
if (try_read) {
|
||||
r = read(fd, (unsigned char *)tmpbuf + n,
|
||||
ENTROPY_NEEDED - n);
|
||||
if (r > 0)
|
||||
n += r;
|
||||
} else
|
||||
r = -1;
|
||||
|
||||
/*
|
||||
* Some Unixen will update t in select(), some won't. For
|
||||
* those who won't, or if we didn't use select() in the first
|
||||
* place, give up here, otherwise, we will do this once again
|
||||
* for the remaining time.
|
||||
*/
|
||||
if (usec == 10 * 1000)
|
||||
usec = 0;
|
||||
}
|
||||
while ((r > 0 ||
|
||||
(errno == EINTR || errno == EAGAIN)) && usec != 0
|
||||
&& n < ENTROPY_NEEDED);
|
||||
|
||||
close(fd);
|
||||
bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/);
|
||||
}
|
||||
}
|
||||
# endif /* defined(DEVRANDOM) */
|
||||
# endif
|
||||
|
||||
# if !defined(OPENSSL_NO_EGD) && defined(DEVRANDOM_EGD)
|
||||
/*
|
||||
* Use an EGD socket to read entropy from an EGD or PRNGD entropy
|
||||
* collecting daemon.
|
||||
*/
|
||||
# ifdef OPENSSL_RAND_SEED_RDTSC
|
||||
entropy_available = rand_acquire_entropy_from_tsc(pool);
|
||||
if (entropy_available > 0)
|
||||
return entropy_available;
|
||||
# endif
|
||||
|
||||
for (egdsocket = egdsockets; *egdsocket && n < ENTROPY_NEEDED;
|
||||
egdsocket++) {
|
||||
int r;
|
||||
# ifdef OPENSSL_RAND_SEED_RDCPU
|
||||
entropy_available = rand_acquire_entropy_from_cpu(pool);
|
||||
if (entropy_available > 0)
|
||||
return entropy_available;
|
||||
# endif
|
||||
|
||||
r = RAND_query_egd_bytes(*egdsocket, (unsigned char *)tmpbuf + n,
|
||||
ENTROPY_NEEDED - n);
|
||||
if (r > 0)
|
||||
n += r;
|
||||
# ifdef OPENSSL_RAND_SEED_EGD
|
||||
bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/);
|
||||
if (bytes_needed > 0) {
|
||||
static const char *paths[] = { DEVRANDOM_EGD, NULL };
|
||||
int i;
|
||||
|
||||
for (i = 0; paths[i] != NULL; i++) {
|
||||
buffer = RAND_POOL_add_begin(pool, bytes_needed);
|
||||
if (buffer != NULL) {
|
||||
size_t bytes = 0;
|
||||
int num = RAND_query_egd_bytes(paths[i],
|
||||
buffer, (int)bytes_needed);
|
||||
if (num == (int)bytes_needed)
|
||||
bytes = bytes_needed;
|
||||
|
||||
entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes);
|
||||
}
|
||||
if (entropy_available > 0)
|
||||
return entropy_available;
|
||||
}
|
||||
}
|
||||
# endif /* defined(DEVRANDOM_EGD) */
|
||||
# endif
|
||||
|
||||
# if defined(DEVRANDOM) || (!defined(OPENSSL_NO_EGD) && defined(DEVRANDOM_EGD))
|
||||
if (n > 0) {
|
||||
RAND_add(tmpbuf, sizeof(tmpbuf), (double)n);
|
||||
OPENSSL_cleanse(tmpbuf, n);
|
||||
}
|
||||
# endif
|
||||
|
||||
/* put in some default random data, we need more than just this */
|
||||
l = curr_pid;
|
||||
RAND_add(&l, sizeof(l), 0.0);
|
||||
l = getuid();
|
||||
RAND_add(&l, sizeof(l), 0.0);
|
||||
|
||||
l = time(NULL);
|
||||
RAND_add(&l, sizeof(l), 0.0);
|
||||
|
||||
# if defined(DEVRANDOM) || (!defined(OPENSSL_NO_EGD) && defined(DEVRANDOM_EGD))
|
||||
return 1;
|
||||
# else
|
||||
return 0;
|
||||
return RAND_POOL_entropy_available(pool);
|
||||
# endif
|
||||
}
|
||||
# endif
|
||||
|
||||
# endif /* defined(__OpenBSD__) */
|
||||
#endif /* !(defined(OPENSSL_SYS_WINDOWS) ||
|
||||
* defined(OPENSSL_SYS_WIN32) ||
|
||||
* defined(OPENSSL_SYS_VMS) ||
|
||||
* defined(OPENSSL_SYS_VXWORKS) */
|
||||
|
||||
#if defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)
|
||||
int RAND_poll(void)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
+47
-55
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
|
||||
* Copyright 2001-2017 The OpenSSL Project Authors. All Rights Reserved.
|
||||
*
|
||||
* Licensed under the OpenSSL license (the "License"). You may not use
|
||||
* this file except in compliance with the License. You can obtain a copy
|
||||
@@ -7,16 +7,11 @@
|
||||
* https://www.openssl.org/source/license.html
|
||||
*/
|
||||
|
||||
/*
|
||||
* Modified by VMS Software, Inc (2016)
|
||||
* Eliminate looping through all processes (performance)
|
||||
* Add additional randomizations using rand() function
|
||||
*/
|
||||
|
||||
#include <openssl/rand.h>
|
||||
#include "rand_lcl.h"
|
||||
#include "e_os.h"
|
||||
|
||||
#if defined(OPENSSL_SYS_VMS)
|
||||
# include <openssl/rand.h>
|
||||
# include "rand_lcl.h"
|
||||
# include <descrip.h>
|
||||
# include <jpidef.h>
|
||||
# include <ssdef.h>
|
||||
@@ -26,6 +21,10 @@
|
||||
# pragma message disable DOLLARID
|
||||
# endif
|
||||
|
||||
# ifndef OPENSSL_RAND_SEED_OS
|
||||
# error "Unsupported seeding method configured; must be os"
|
||||
# endif
|
||||
|
||||
/*
|
||||
* Use 32-bit pointers almost everywhere. Define the type to which to cast a
|
||||
* pointer passed to an external function.
|
||||
@@ -34,9 +33,9 @@
|
||||
# define PTR_T __void_ptr64
|
||||
# pragma pointer_size save
|
||||
# pragma pointer_size 32
|
||||
# else /* __INITIAL_POINTER_SIZE == 64 */
|
||||
# else
|
||||
# define PTR_T void *
|
||||
# endif /* __INITIAL_POINTER_SIZE == 64 [else] */
|
||||
# endif
|
||||
|
||||
static struct items_data_st {
|
||||
short length, code; /* length is number of bytes */
|
||||
@@ -52,27 +51,22 @@ static struct items_data_st {
|
||||
{4, JPI$_PPGCNT},
|
||||
{4, JPI$_WSPEAK},
|
||||
{4, JPI$_FINALEXC},
|
||||
{0, 0} /* zero terminated */
|
||||
{0, 0}
|
||||
};
|
||||
|
||||
int RAND_poll(void)
|
||||
size_t RAND_POOL_acquire_entropy(RAND_POOL *pool)
|
||||
{
|
||||
|
||||
/* determine the number of items in the JPI array */
|
||||
|
||||
struct items_data_st item_entry;
|
||||
int item_entry_count = sizeof(items_data)/sizeof(item_entry);
|
||||
|
||||
int item_entry_count = OSSL_NELEM(items_data);
|
||||
/* Create the JPI itemlist array to hold item_data content */
|
||||
|
||||
struct {
|
||||
short length, code;
|
||||
int *buffer;
|
||||
int *retlen;
|
||||
} item[item_entry_count], *pitem; /* number of entries in items_data */
|
||||
|
||||
} item[item_entry_count], *pitem;
|
||||
struct items_data_st *pitems_data;
|
||||
int data_buffer[(item_entry_count*2)+4]; /* 8 bytes per entry max */
|
||||
int data_buffer[(item_entry_count * 2) + 4]; /* 8 bytes per entry max */
|
||||
int iosb[2];
|
||||
int sys_time[2];
|
||||
int *ptr;
|
||||
@@ -80,54 +74,52 @@ int RAND_poll(void)
|
||||
int tmp_length = 0;
|
||||
int total_length = 0;
|
||||
|
||||
pitems_data = items_data;
|
||||
pitem = item;
|
||||
|
||||
|
||||
/* Setup itemlist for GETJPI */
|
||||
while (pitems_data->length) {
|
||||
pitems_data = items_data;
|
||||
for (pitem = item; pitems_data->length != 0; pitem++) {
|
||||
pitem->length = pitems_data->length;
|
||||
pitem->code = pitems_data->code;
|
||||
pitem->buffer = &data_buffer[total_length];
|
||||
pitem->retlen = 0;
|
||||
/* total_length is in longwords */
|
||||
total_length += pitems_data->length/4;
|
||||
total_length += pitems_data->length / 4;
|
||||
pitems_data++;
|
||||
pitem ++;
|
||||
}
|
||||
pitem->length = pitem->code = 0;
|
||||
|
||||
/* Fill data_buffer with various info bits from this process */
|
||||
/* and twist that data to seed the SSL random number init */
|
||||
|
||||
if (sys$getjpiw(EFN$C_ENF, NULL, NULL, item, &iosb, 0, 0) == SS$_NORMAL) {
|
||||
for (i = 0; i < total_length; i++) {
|
||||
sys$gettim((struct _generic_64 *)&sys_time[0]);
|
||||
srand(sys_time[0] * data_buffer[0] * data_buffer[1] + i);
|
||||
|
||||
if (i == (total_length - 1)) { /* for JPI$_FINALEXC */
|
||||
ptr = &data_buffer[i];
|
||||
for (j = 0; j < 4; j++) {
|
||||
data_buffer[i + j] = ptr[j];
|
||||
/* OK to use rand() just to scramble the seed */
|
||||
data_buffer[i + j] ^= (sys_time[0] ^ rand());
|
||||
tmp_length++;
|
||||
}
|
||||
} else {
|
||||
/* OK to use rand() just to scramble the seed */
|
||||
data_buffer[i] ^= (sys_time[0] ^ rand());
|
||||
}
|
||||
}
|
||||
|
||||
total_length += (tmp_length - 1);
|
||||
|
||||
/* size of seed is total_length*4 bytes (64bytes) */
|
||||
RAND_add((PTR_T) data_buffer, total_length*4, total_length * 2);
|
||||
} else {
|
||||
if (sys$getjpiw(EFN$C_ENF, NULL, NULL, item, &iosb, 0, 0) != SS$_NORMAL)
|
||||
return 0;
|
||||
|
||||
/* Now twist that data to seed the SSL random number init */
|
||||
for (i = 0; i < total_length; i++) {
|
||||
sys$gettim((struct _generic_64 *)&sys_time[0]);
|
||||
srand(sys_time[0] * data_buffer[0] * data_buffer[1] + i);
|
||||
|
||||
if (i == (total_length - 1)) { /* for JPI$_FINALEXC */
|
||||
ptr = &data_buffer[i];
|
||||
for (j = 0; j < 4; j++) {
|
||||
data_buffer[i + j] = ptr[j];
|
||||
/* OK to use rand() just to scramble the seed */
|
||||
data_buffer[i + j] ^= (sys_time[0] ^ rand());
|
||||
tmp_length++;
|
||||
}
|
||||
} else {
|
||||
/* OK to use rand() just to scramble the seed */
|
||||
data_buffer[i] ^= (sys_time[0] ^ rand());
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
total_length += (tmp_length - 1);
|
||||
|
||||
/*
|
||||
* Size of seed is total_length*4 bytes (64bytes). The original assumption
|
||||
* was that it contains 4 bits of entropy per byte. This makes a total
|
||||
* amount of total_length*16 bits (256bits).
|
||||
*/
|
||||
return RAND_POOL_add(pool,
|
||||
(PTR_T)data_buffer, total_length * 4,
|
||||
total_length * 16);
|
||||
}
|
||||
|
||||
#endif
|
||||
+76
-81
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
|
||||
* Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
|
||||
*
|
||||
* Licensed under the OpenSSL license (the "License"). You may not use
|
||||
* this file except in compliance with the License. You can obtain a copy
|
||||
@@ -10,15 +10,19 @@
|
||||
#include "internal/cryptlib.h"
|
||||
#include <openssl/rand.h>
|
||||
#include "rand_lcl.h"
|
||||
|
||||
#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32)
|
||||
# include <windows.h>
|
||||
/* On Windows 7 or higher use BCrypt instead of the legacy CryptoAPI */
|
||||
# if defined(_MSC_VER) && defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0601
|
||||
# define RAND_WINDOWS_USE_BCRYPT
|
||||
|
||||
# ifndef OPENSSL_RAND_SEED_OS
|
||||
# error "Unsupported seeding method configured; must be os"
|
||||
# endif
|
||||
|
||||
# ifdef RAND_WINDOWS_USE_BCRYPT
|
||||
# include <windows.h>
|
||||
/* On Windows 7 or higher use BCrypt instead of the legacy CryptoAPI */
|
||||
# if defined(_MSC_VER) && defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0601
|
||||
# define USE_BCRYPTGENRANDOM
|
||||
# endif
|
||||
|
||||
# ifdef USE_BCRYPTGENRANDOM
|
||||
# include <bcrypt.h>
|
||||
# pragma comment(lib, "bcrypt.lib")
|
||||
# ifndef STATUS_SUCCESS
|
||||
@@ -34,55 +38,83 @@
|
||||
# define INTEL_DEF_PROV L"Intel Hardware Cryptographic Service Provider"
|
||||
# endif
|
||||
|
||||
static void readtimer(void);
|
||||
|
||||
int RAND_poll(void)
|
||||
size_t RAND_POOL_acquire_entropy(RAND_POOL *pool)
|
||||
{
|
||||
MEMORYSTATUS mst;
|
||||
# ifndef RAND_WINDOWS_USE_BCRYPT
|
||||
# ifndef USE_BCRYPTGENRANDOM
|
||||
HCRYPTPROV hProvider;
|
||||
# endif
|
||||
DWORD w;
|
||||
BYTE buf[64];
|
||||
unsigned char *buffer;
|
||||
size_t bytes_needed;
|
||||
size_t entropy_available = 0;
|
||||
|
||||
# ifdef RAND_WINDOWS_USE_BCRYPT
|
||||
if (BCryptGenRandom(NULL, buf, (ULONG)sizeof(buf), BCRYPT_USE_SYSTEM_PREFERRED_RNG) == STATUS_SUCCESS) {
|
||||
RAND_add(buf, sizeof(buf), sizeof(buf));
|
||||
}
|
||||
# else
|
||||
/* poll the CryptoAPI PRNG */
|
||||
/* The CryptoAPI returns sizeof(buf) bytes of randomness */
|
||||
if (CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
|
||||
if (CryptGenRandom(hProvider, (DWORD)sizeof(buf), buf) != 0) {
|
||||
RAND_add(buf, sizeof(buf), sizeof(buf));
|
||||
}
|
||||
CryptReleaseContext(hProvider, 0);
|
||||
}
|
||||
|
||||
/* poll the Pentium PRG with CryptoAPI */
|
||||
if (CryptAcquireContextW(&hProvider, NULL, INTEL_DEF_PROV, PROV_INTEL_SEC, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
|
||||
if (CryptGenRandom(hProvider, (DWORD)sizeof(buf), buf) != 0) {
|
||||
RAND_add(buf, sizeof(buf), sizeof(buf));
|
||||
}
|
||||
CryptReleaseContext(hProvider, 0);
|
||||
}
|
||||
# ifdef OPENSSL_RAND_SEED_RDTSC
|
||||
entropy_available = rand_acquire_entropy_from_tsc(pool);
|
||||
if (entropy_available > 0)
|
||||
return entropy_available;
|
||||
# endif
|
||||
|
||||
/* timer data */
|
||||
readtimer();
|
||||
# ifdef OPENSSL_RAND_SEED_RDCPU
|
||||
entropy_available = rand_acquire_entropy_from_cpu(pool);
|
||||
if (entropy_available > 0)
|
||||
return entropy_available;
|
||||
# endif
|
||||
|
||||
/* memory usage statistics */
|
||||
GlobalMemoryStatus(&mst);
|
||||
RAND_add(&mst, sizeof(mst), 1);
|
||||
# ifdef USE_BCRYPTGENRANDOM
|
||||
bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/);
|
||||
buffer = RAND_POOL_add_begin(pool, bytes_needed);
|
||||
if (buffer != NULL) {
|
||||
size_t bytes = 0;
|
||||
if (BCryptGenRandom(NULL, buffer, bytes_needed,
|
||||
BCRYPT_USE_SYSTEM_PREFERRED_RNG) == STATUS_SUCCESS)
|
||||
bytes = bytes_needed;
|
||||
|
||||
/* process ID */
|
||||
w = GetCurrentProcessId();
|
||||
RAND_add(&w, sizeof(w), 1);
|
||||
entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes);
|
||||
}
|
||||
if (entropy_available > 0)
|
||||
return entropy_available;
|
||||
# else
|
||||
bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/);
|
||||
buffer = RAND_POOL_add_begin(pool, bytes_needed);
|
||||
if (buffer != NULL) {
|
||||
size_t bytes = 0;
|
||||
/* poll the CryptoAPI PRNG */
|
||||
if (CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL,
|
||||
CRYPT_VERIFYCONTEXT | CRYPT_SILENT) != 0) {
|
||||
if (CryptGenRandom(hProvider, bytes_needed, buffer) != 0)
|
||||
bytes = bytes_needed;
|
||||
|
||||
return (1);
|
||||
CryptReleaseContext(hProvider, 0);
|
||||
}
|
||||
|
||||
entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes);
|
||||
}
|
||||
if (entropy_available > 0)
|
||||
return entropy_available;
|
||||
|
||||
bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/);
|
||||
buffer = RAND_POOL_add_begin(pool, bytes_needed);
|
||||
if (buffer != NULL) {
|
||||
size_t bytes = 0;
|
||||
/* poll the Pentium PRG with CryptoAPI */
|
||||
if (CryptAcquireContextW(&hProvider, NULL,
|
||||
INTEL_DEF_PROV, PROV_INTEL_SEC,
|
||||
CRYPT_VERIFYCONTEXT | CRYPT_SILENT) != 0) {
|
||||
if (CryptGenRandom(hProvider, bytes_needed, buffer) != 0)
|
||||
bytes = bytes_needed;
|
||||
|
||||
CryptReleaseContext(hProvider, 0);
|
||||
}
|
||||
entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes);
|
||||
}
|
||||
if (entropy_available > 0)
|
||||
return entropy_available;
|
||||
# endif
|
||||
|
||||
return RAND_POOL_entropy_available(pool);
|
||||
}
|
||||
|
||||
#if OPENSSL_API_COMPAT < 0x10100000L
|
||||
# if OPENSSL_API_COMPAT < 0x10100000L
|
||||
int RAND_event(UINT iMsg, WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
RAND_poll();
|
||||
@@ -93,43 +125,6 @@ void RAND_screen(void)
|
||||
{
|
||||
RAND_poll();
|
||||
}
|
||||
#endif
|
||||
|
||||
/* feed timing information to the PRNG */
|
||||
static void readtimer(void)
|
||||
{
|
||||
DWORD w;
|
||||
LARGE_INTEGER l;
|
||||
static int have_perfc = 1;
|
||||
# if defined(_MSC_VER) && defined(_M_X86)
|
||||
static int have_tsc = 1;
|
||||
DWORD cyclecount;
|
||||
|
||||
if (have_tsc) {
|
||||
__try {
|
||||
__asm {
|
||||
_emit 0x0f _emit 0x31 mov cyclecount, eax}
|
||||
RAND_add(&cyclecount, sizeof(cyclecount), 1);
|
||||
}
|
||||
__except(EXCEPTION_EXECUTE_HANDLER) {
|
||||
have_tsc = 0;
|
||||
}
|
||||
}
|
||||
# else
|
||||
# define have_tsc 0
|
||||
# endif
|
||||
|
||||
if (have_perfc) {
|
||||
if (QueryPerformanceCounter(&l) == 0)
|
||||
have_perfc = 0;
|
||||
else
|
||||
RAND_add(&l, sizeof(l), 0);
|
||||
}
|
||||
|
||||
if (!have_tsc && !have_perfc) {
|
||||
w = GetTickCount();
|
||||
RAND_add(&w, sizeof(w), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
+103
-204
@@ -25,6 +25,11 @@
|
||||
#ifndef OPENSSL_NO_POSIX_IO
|
||||
# include <sys/stat.h>
|
||||
# include <fcntl.h>
|
||||
# ifdef _WIN32
|
||||
# include <io.h>
|
||||
# endif
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Following should not be needed, and we could have been stricter
|
||||
* and demand S_IS*. But some systems just don't comply... Formally
|
||||
@@ -32,184 +37,106 @@
|
||||
* would look like ((m) & MASK == TYPE), but since MASK availability
|
||||
* is as questionable, we settle for this poor-man fallback...
|
||||
*/
|
||||
# if !defined(S_ISBLK)
|
||||
# if defined(_S_IFBLK)
|
||||
# define S_ISBLK(m) ((m) & _S_IFBLK)
|
||||
# elif defined(S_IFBLK)
|
||||
# define S_ISBLK(m) ((m) & S_IFBLK)
|
||||
# elif defined(_WIN32)
|
||||
# define S_ISBLK(m) 0 /* no concept of block devices on Windows */
|
||||
# endif
|
||||
# if !defined(S_ISREG)
|
||||
# define S_ISREG(m) ((m) & S_IFREG)
|
||||
# endif
|
||||
# if !defined(S_ISCHR)
|
||||
# if defined(_S_IFCHR)
|
||||
# define S_ISCHR(m) ((m) & _S_IFCHR)
|
||||
# elif defined(S_IFCHR)
|
||||
# define S_ISCHR(m) ((m) & S_IFCHR)
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
# define stat _stat
|
||||
# define chmod _chmod
|
||||
# define open _open
|
||||
# define fdopen _fdopen
|
||||
# define fstat _fstat
|
||||
# define fileno _fileno
|
||||
#endif
|
||||
|
||||
#undef BUFSIZE
|
||||
#define BUFSIZE 1024
|
||||
#define RAND_DATA 1024
|
||||
#define RAND_FILE_SIZE 1024
|
||||
#define RFILE ".rnd"
|
||||
|
||||
#ifdef OPENSSL_SYS_VMS
|
||||
/*
|
||||
* Misc hacks needed for specific cases.
|
||||
*
|
||||
* __FILE_ptr32 is a type provided by DEC C headers (types.h specifically)
|
||||
* to make sure the FILE* is a 32-bit pointer no matter what. We know that
|
||||
* stdio function return this type (a study of stdio.h proves it).
|
||||
* Additionally, we create a similar char pointer type for the sake of
|
||||
* vms_setbuf below.
|
||||
*/
|
||||
# if __INITIAL_POINTER_SIZE == 64
|
||||
# pragma pointer_size save
|
||||
# pragma pointer_size 32
|
||||
typedef char *char_ptr32;
|
||||
# pragma pointer_size restore
|
||||
/*
|
||||
* On VMS, setbuf() will only take 32-bit pointers, and a compilation
|
||||
* with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
|
||||
* Since we know that the FILE* really is a 32-bit pointer expanded to
|
||||
* 64 bits, we also know it's safe to convert it back to a 32-bit pointer.
|
||||
* As for the buffer parameter, we only use NULL here, so that passes as
|
||||
* well...
|
||||
*/
|
||||
# define setbuf(fp,buf) (setbuf)((__FILE_ptr32)(fp), (char_ptr32)(buf))
|
||||
# endif
|
||||
|
||||
/*
|
||||
* stdio functions return this type (a study of stdio.h proves it).
|
||||
*
|
||||
* This declaration is a nasty hack to get around vms' extension to fopen for
|
||||
* passing in sharing options being disabled by /STANDARD=ANSI89
|
||||
*/
|
||||
static __FILE_ptr32 (*const vms_fopen)(const char *, const char *, ...) =
|
||||
(__FILE_ptr32 (*)(const char *, const char *, ...))fopen;
|
||||
# define VMS_OPEN_ATTRS "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0"
|
||||
|
||||
# define openssl_fopen(fname,mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS)
|
||||
(__FILE_ptr32 (*)(const char *, const char *, ...))fopen;
|
||||
# define VMS_OPEN_ATTRS \
|
||||
"shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0"
|
||||
# define openssl_fopen(fname, mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS)
|
||||
#endif
|
||||
|
||||
#define RFILE ".rnd"
|
||||
|
||||
/*
|
||||
* Note that these functions are intended for seed files only. Entropy
|
||||
* devices and EGD sockets are handled in rand_unix.c
|
||||
* devices and EGD sockets are handled in rand_unix.c If |bytes| is
|
||||
* -1 read the complete file; otherwise read the specified amount.
|
||||
*/
|
||||
|
||||
int RAND_load_file(const char *file, long bytes)
|
||||
{
|
||||
/*-
|
||||
* If bytes >= 0, read up to 'bytes' bytes.
|
||||
* if bytes == -1, read complete file.
|
||||
*/
|
||||
|
||||
unsigned char buf[BUFSIZE];
|
||||
unsigned char buf[RAND_FILE_SIZE];
|
||||
#ifndef OPENSSL_NO_POSIX_IO
|
||||
struct stat sb;
|
||||
#endif
|
||||
int i, ret = 0, n;
|
||||
FILE *in = NULL;
|
||||
|
||||
if (file == NULL)
|
||||
return 0;
|
||||
int i, n, ret = 0;
|
||||
FILE *in;
|
||||
|
||||
if (bytes == 0)
|
||||
return ret;
|
||||
|
||||
in = openssl_fopen(file, "rb");
|
||||
if (in == NULL)
|
||||
goto err;
|
||||
return 0;
|
||||
|
||||
#ifndef OPENSSL_NO_POSIX_IO
|
||||
/*
|
||||
* struct stat can have padding and unused fields that may not be
|
||||
* initialized in the call to stat(). We need to clear the entire
|
||||
* structure before calling RAND_add() to avoid complaints from
|
||||
* applications such as Valgrind.
|
||||
*/
|
||||
memset(&sb, 0, sizeof(sb));
|
||||
if (fstat(fileno(in), &sb) < 0)
|
||||
goto err;
|
||||
RAND_add(&sb, sizeof(sb), 0.0);
|
||||
|
||||
# if defined(S_ISBLK) && defined(S_ISCHR)
|
||||
if (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode)) {
|
||||
/*
|
||||
* this file is a device. we don't want read an infinite number of
|
||||
* bytes from a random device, nor do we want to use buffered I/O
|
||||
* because we will waste system entropy.
|
||||
*/
|
||||
bytes = (bytes == -1) ? 2048 : bytes; /* ok, is 2048 enough? */
|
||||
setbuf(in, NULL); /* don't do buffered reads */
|
||||
if (stat(file, &sb) < 0 || !S_ISREG(sb.st_mode)) {
|
||||
RANDerr(RAND_F_RAND_LOAD_FILE, RAND_R_NOT_A_REGULAR_FILE);
|
||||
ERR_add_error_data(2, "Filename=", file);
|
||||
return -1;
|
||||
}
|
||||
# endif
|
||||
#endif
|
||||
for (;;) {
|
||||
if ((in = openssl_fopen(file, "rb")) == NULL) {
|
||||
RANDerr(RAND_F_RAND_LOAD_FILE, RAND_R_CANNOT_OPEN_FILE);
|
||||
ERR_add_error_data(2, "Filename=", file);
|
||||
return -1;
|
||||
}
|
||||
|
||||
for ( ; ; ) {
|
||||
if (bytes > 0)
|
||||
n = (bytes < BUFSIZE) ? (int)bytes : BUFSIZE;
|
||||
n = (bytes < RAND_FILE_SIZE) ? (int)bytes : RAND_FILE_SIZE;
|
||||
else
|
||||
n = BUFSIZE;
|
||||
n = RAND_FILE_SIZE;
|
||||
i = fread(buf, 1, n, in);
|
||||
if (i <= 0)
|
||||
break;
|
||||
|
||||
RAND_add(buf, i, (double)i);
|
||||
ret += i;
|
||||
if (bytes > 0) {
|
||||
bytes -= n;
|
||||
if (bytes <= 0)
|
||||
break;
|
||||
}
|
||||
|
||||
/* If given a bytecount, and we did it, break. */
|
||||
if (bytes > 0 && (bytes -= i) <= 0)
|
||||
break;
|
||||
}
|
||||
OPENSSL_cleanse(buf, BUFSIZE);
|
||||
err:
|
||||
if (in != NULL)
|
||||
fclose(in);
|
||||
|
||||
OPENSSL_cleanse(buf, sizeof(buf));
|
||||
fclose(in);
|
||||
return ret;
|
||||
}
|
||||
|
||||
int RAND_write_file(const char *file)
|
||||
{
|
||||
unsigned char buf[BUFSIZE];
|
||||
int i, ret = 0, rand_err = 0;
|
||||
unsigned char buf[RAND_FILE_SIZE];
|
||||
int ret = -1;
|
||||
FILE *out = NULL;
|
||||
int n;
|
||||
#ifndef OPENSSL_NO_POSIX_IO
|
||||
struct stat sb;
|
||||
|
||||
# if defined(S_ISBLK) && defined(S_ISCHR)
|
||||
# ifdef _WIN32
|
||||
/*
|
||||
* Check for |file| being a driver as "ASCII-safe" on Windows,
|
||||
* because driver paths are always ASCII.
|
||||
*/
|
||||
# endif
|
||||
i = stat(file, &sb);
|
||||
if (i != -1) {
|
||||
if (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode)) {
|
||||
/*
|
||||
* this file is a device. we don't write back to it. we
|
||||
* "succeed" on the assumption this is some sort of random
|
||||
* device. Otherwise attempting to write to and chmod the device
|
||||
* causes problems.
|
||||
*/
|
||||
return 1;
|
||||
}
|
||||
if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) {
|
||||
RANDerr(RAND_F_RAND_WRITE_FILE, RAND_R_NOT_A_REGULAR_FILE);
|
||||
ERR_add_error_data(2, "Filename=", file);
|
||||
return -1;
|
||||
}
|
||||
# endif
|
||||
#endif
|
||||
|
||||
/* Collect enough random data. */
|
||||
if (RAND_bytes(buf, (int)sizeof(buf)) != 1)
|
||||
return -1;
|
||||
|
||||
#if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
|
||||
!defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
|
||||
{
|
||||
@@ -244,69 +171,57 @@ int RAND_write_file(const char *file)
|
||||
* application level. Also consider whether or not you NEED a persistent
|
||||
* rand file in a concurrent use situation.
|
||||
*/
|
||||
|
||||
out = openssl_fopen(file, "rb+");
|
||||
#endif
|
||||
|
||||
if (out == NULL)
|
||||
out = openssl_fopen(file, "wb");
|
||||
if (out == NULL)
|
||||
goto err;
|
||||
|
||||
#if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
|
||||
chmod(file, 0600);
|
||||
#endif
|
||||
n = RAND_DATA;
|
||||
for (;;) {
|
||||
i = (n > BUFSIZE) ? BUFSIZE : n;
|
||||
n -= BUFSIZE;
|
||||
if (RAND_bytes(buf, i) <= 0)
|
||||
rand_err = 1;
|
||||
i = fwrite(buf, 1, i, out);
|
||||
if (i <= 0) {
|
||||
ret = 0;
|
||||
break;
|
||||
}
|
||||
ret += i;
|
||||
if (n <= 0)
|
||||
break;
|
||||
if (out == NULL) {
|
||||
RANDerr(RAND_F_RAND_WRITE_FILE, RAND_R_CANNOT_OPEN_FILE);
|
||||
ERR_add_error_data(2, "Filename=", file);
|
||||
return -1;
|
||||
}
|
||||
|
||||
#if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
|
||||
/*
|
||||
* Yes it's late to do this (see above comment), but better than nothing.
|
||||
*/
|
||||
chmod(file, 0600);
|
||||
#endif
|
||||
|
||||
ret = fwrite(buf, 1, RAND_FILE_SIZE, out);
|
||||
fclose(out);
|
||||
OPENSSL_cleanse(buf, BUFSIZE);
|
||||
err:
|
||||
return (rand_err ? -1 : ret);
|
||||
OPENSSL_cleanse(buf, RAND_FILE_SIZE);
|
||||
return ret;
|
||||
}
|
||||
|
||||
const char *RAND_file_name(char *buf, size_t size)
|
||||
{
|
||||
char *s = NULL;
|
||||
size_t len;
|
||||
int use_randfile = 1;
|
||||
#ifdef __OpenBSD__
|
||||
struct stat sb;
|
||||
#endif
|
||||
|
||||
#if defined(_WIN32) && defined(CP_UTF8)
|
||||
DWORD len;
|
||||
WCHAR *var, *val;
|
||||
DWORD envlen;
|
||||
WCHAR *var;
|
||||
|
||||
if ((var = L"RANDFILE",
|
||||
len = GetEnvironmentVariableW(var, NULL, 0)) == 0
|
||||
&& (var = L"HOME", use_randfile = 0,
|
||||
len = GetEnvironmentVariableW(var, NULL, 0)) == 0
|
||||
&& (var = L"USERPROFILE",
|
||||
len = GetEnvironmentVariableW(var, NULL, 0)) == 0) {
|
||||
var = L"SYSTEMROOT",
|
||||
len = GetEnvironmentVariableW(var, NULL, 0);
|
||||
/* Look up various environment variables. */
|
||||
if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) {
|
||||
use_randfile = 0;
|
||||
if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0
|
||||
&& (envlen = GetEnvironmentVariableW(var = L"USERPROFILE",
|
||||
NULL, 0)) == 0)
|
||||
envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0);
|
||||
}
|
||||
|
||||
if (len != 0) {
|
||||
/* If we got a value, allocate space to hold it and then get it. */
|
||||
if (envlen != 0) {
|
||||
int sz;
|
||||
WCHAR *val = _alloca(envlen * sizeof(WCHAR));
|
||||
|
||||
val = _alloca(len * sizeof(WCHAR));
|
||||
|
||||
if (GetEnvironmentVariableW(var, val, len) < len
|
||||
&& (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
|
||||
NULL, NULL)) != 0) {
|
||||
if (GetEnvironmentVariableW(var, val, envlen) < envlen
|
||||
&& (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
|
||||
NULL, NULL)) != 0) {
|
||||
s = _alloca(sz);
|
||||
if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz,
|
||||
NULL, NULL) == 0)
|
||||
@@ -316,49 +231,33 @@ const char *RAND_file_name(char *buf, size_t size)
|
||||
#else
|
||||
if (OPENSSL_issetugid() != 0) {
|
||||
use_randfile = 0;
|
||||
} else {
|
||||
s = getenv("RANDFILE");
|
||||
if (s == NULL || *s == '\0') {
|
||||
use_randfile = 0;
|
||||
s = getenv("HOME");
|
||||
}
|
||||
} else if ((s = getenv("RANDFILE")) == NULL || *s == '\0') {
|
||||
use_randfile = 0;
|
||||
s = getenv("HOME");
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef DEFAULT_HOME
|
||||
if (!use_randfile && s == NULL) {
|
||||
if (!use_randfile && s == NULL)
|
||||
s = DEFAULT_HOME;
|
||||
}
|
||||
#endif
|
||||
if (s != NULL && *s) {
|
||||
size_t len = strlen(s);
|
||||
if (s == NULL || *s == '\0')
|
||||
return NULL;
|
||||
|
||||
if (use_randfile && len + 1 < size) {
|
||||
if (OPENSSL_strlcpy(buf, s, size) >= size)
|
||||
return NULL;
|
||||
} else if (len + strlen(RFILE) + 2 < size) {
|
||||
OPENSSL_strlcpy(buf, s, size);
|
||||
#ifndef OPENSSL_SYS_VMS
|
||||
OPENSSL_strlcat(buf, "/", size);
|
||||
#endif
|
||||
OPENSSL_strlcat(buf, RFILE, size);
|
||||
}
|
||||
} else {
|
||||
buf[0] = '\0'; /* no file name */
|
||||
}
|
||||
|
||||
#ifdef __OpenBSD__
|
||||
/*
|
||||
* given that all random loads just fail if the file can't be seen on a
|
||||
* stat, we stat the file we're returning, if it fails, use /dev/arandom
|
||||
* instead. this allows the user to use their own source for good random
|
||||
* data, but defaults to something hopefully decent if that isn't
|
||||
* available.
|
||||
*/
|
||||
|
||||
if (!buf[0] || stat(buf, &sb) == -1)
|
||||
if (OPENSSL_strlcpy(buf, "/dev/arandom", size) >= size) {
|
||||
len = strlen(s);
|
||||
if (use_randfile) {
|
||||
if (len + 1 >= size)
|
||||
return NULL;
|
||||
}
|
||||
strcpy(buf, s);
|
||||
} else {
|
||||
if (len + 1 + strlen(RFILE) + 1 >= size)
|
||||
return NULL;
|
||||
strcpy(buf, s);
|
||||
#ifndef OPENSSL_SYS_VMS
|
||||
strcat(buf, "/");
|
||||
#endif
|
||||
return buf[0] ? buf : NULL;
|
||||
strcat(buf, RFILE);
|
||||
}
|
||||
|
||||
return buf;
|
||||
}
|
||||
Reference in New Issue
Block a user