| 1 |
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. |
| 2 |
// SPDX-License-Identifier: Apache-2.0 OR ISC |
| 3 |
|
| 4 |
#if !defined(_DEFAULT_SOURCE) |
| 5 |
// Needed for getentropy on musl and glibc per man pages. |
| 6 |
#define _DEFAULT_SOURCE |
| 7 |
#endif |
| 8 |
|
| 9 |
#include <openssl/rand.h> |
| 10 |
|
| 11 |
#include "internal.h" |
| 12 |
|
| 13 |
#if defined(OPENSSL_RAND_GETENTROPY) |
| 14 |
|
| 15 |
#include <limits.h> |
| 16 |
#include <stdio.h> |
| 17 |
#include <stdlib.h> |
| 18 |
#include <unistd.h> |
| 19 |
|
| 20 |
#if defined(OPENSSL_MACOS) |
| 21 |
// MacOS does not declare getentropy in uinstd.h like other OS's. |
| 22 |
#include <sys/random.h> |
| 23 |
#endif |
| 24 |
|
| 25 |
#if !defined(GETENTROPY_MAX) |
| 26 |
// Per POSIX 2024 |
| 27 |
// https://pubs.opengroup.org/onlinepubs/9799919799/functions/getentropy.html |
| 28 |
#define GETENTROPY_MAX 256 |
| 29 |
#endif |
| 30 |
|
| 31 |
void CRYPTO_sysrand(uint8_t *out, size_t requested) { |
| 32 |
// getentropy max request size is GETENTROPY_MAX. |
| 33 |
while (requested > 0) { |
| 34 |
size_t request_chunk = (requested > GETENTROPY_MAX) ? GETENTROPY_MAX : requested; |
| 35 |
if (getentropy(out, request_chunk) != 0) { |
| 36 |
fprintf(stderr, "getentropy failed.\n"); |
| 37 |
abort(); |
| 38 |
} |
| 39 |
requested -= request_chunk; |
| 40 |
out += request_chunk; |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
#endif |