#include <openssl/ctrdrbg.h>
#include "../fipsmodule/bcm_interface.h"
#include "../bcm_support.h"
#include "../internal.h"
#if defined(BORINGSSL_FIPS)
static void passive_get_seed_entropy(uint8_t *out_entropy,
size_t out_entropy_len,
int *out_want_additional_input) {
*out_want_additional_input = 0;
if (bcm_success(BCM_rand_bytes_hwrng(out_entropy, out_entropy_len))) {
*out_want_additional_input = 1;
} else {
CRYPTO_sysrand_for_seed(out_entropy, out_entropy_len);
}
}
#define ENTROPY_READ_LEN …
#if defined(OPENSSL_ANDROID)
#include <errno.h>
#include <stdatomic.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
enum socket_history_t {
socket_not_yet_attempted = 0,
socket_success,
socket_failed,
};
static _Atomic enum socket_history_t g_socket_history =
socket_not_yet_attempted;
#define DAEMON_RESPONSE_LEN …
static_assert(ENTROPY_READ_LEN == DAEMON_RESPONSE_LEN,
"entropy daemon response length mismatch");
static int get_seed_from_daemon(uint8_t *out_entropy, size_t out_entropy_len) {
if (out_entropy_len > DAEMON_RESPONSE_LEN) {
abort();
}
const enum socket_history_t socket_history = atomic_load(&g_socket_history);
if (socket_history == socket_failed) {
return 0;
}
int ret = 0;
const int sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock < 0) {
goto out;
}
struct sockaddr_un sun;
memset(&sun, 0, sizeof(sun));
sun.sun_family = AF_UNIX;
static const char kSocketPath[] = "/dev/socket/prng_seeder";
static_assert(sizeof(kSocketPath) <= UNIX_PATH_MAX,
"kSocketPath too long");
OPENSSL_memcpy(sun.sun_path, kSocketPath, sizeof(kSocketPath));
if (connect(sock, (struct sockaddr *)&sun, sizeof(sun))) {
goto out;
}
uint8_t buffer[DAEMON_RESPONSE_LEN];
size_t done = 0;
while (done < sizeof(buffer)) {
ssize_t n;
do {
n = read(sock, buffer + done, sizeof(buffer) - done);
} while (n == -1 && errno == EINTR);
if (n < 1) {
goto out;
}
done += n;
}
if (done != DAEMON_RESPONSE_LEN) {
goto out;
}
assert(out_entropy_len <= DAEMON_RESPONSE_LEN);
OPENSSL_memcpy(out_entropy, buffer, out_entropy_len);
ret = 1;
out:
if (socket_history == socket_not_yet_attempted) {
enum socket_history_t expected = socket_history;
atomic_compare_exchange_strong(&g_socket_history, &expected,
(ret == 0) ? socket_failed : socket_success);
}
close(sock);
return ret;
}
#else
static int get_seed_from_daemon(uint8_t *out_entropy, size_t out_entropy_len) {
return 0;
}
#endif
void RAND_need_entropy(size_t bytes_needed) {
uint8_t buf[ENTROPY_READ_LEN];
size_t todo = sizeof(buf);
if (todo > bytes_needed) {
todo = bytes_needed;
}
int want_additional_input;
if (get_seed_from_daemon(buf, todo)) {
want_additional_input = 1;
} else {
passive_get_seed_entropy(buf, todo, &want_additional_input);
}
if (boringssl_fips_break_test("CRNG")) {
OPENSSL_memset(buf, 0, todo);
}
BCM_rand_load_entropy(buf, todo, want_additional_input);
}
#endif