blob: 7f0c43ac7cb4799063db54026b916a340f7b89f5 [file] [log] [blame]
Bob Beckdbd143c2023-07-31 21:06:03 -07001/* Copyright (c) 2023, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15#if !defined(_DEFAULT_SOURCE)
16#define _DEFAULT_SOURCE // Needed for getentropy on musl and glibc
17#endif
18
19#include <openssl/rand.h>
20
21#include "../fipsmodule/rand/internal.h"
22
23#if defined(OPENSSL_RAND_GETENTROPY)
24
25#include <unistd.h>
26
Bob Beck18b1b8b2023-08-14 14:32:58 -060027#include <errno.h>
Bob Beckdbd143c2023-07-31 21:06:03 -070028
29#if defined(OPENSSL_MACOS) || defined(OPENSSL_FUCHSIA)
30#include <sys/random.h>
31#endif
32
33#include <gtest/gtest.h>
34
35#include <openssl/span.h>
36
37#include "../test/test_util.h"
38
39// This test is, strictly speaking, flaky, but we use large enough buffers
40// that the probability of failing when we should pass is negligible.
41
42TEST(GetEntropyTest, NotObviouslyBroken) {
43 static const uint8_t kZeros[256] = {0};
44
45 uint8_t buf1[256], buf2[256];
46
47 EXPECT_EQ(getentropy(buf1, sizeof(buf1)), 0);
48 EXPECT_EQ(getentropy(buf2, sizeof(buf2)), 0);
49 EXPECT_NE(Bytes(buf1), Bytes(buf2));
50 EXPECT_NE(Bytes(buf1), Bytes(kZeros));
51 EXPECT_NE(Bytes(buf2), Bytes(kZeros));
52 uint8_t buf3[256];
53 // Ensure that the implementation is not simply returning the memory unchanged.
54 memcpy(buf3, buf1, sizeof(buf3));
55 EXPECT_EQ(getentropy(buf1, sizeof(buf1)), 0);
56 EXPECT_NE(Bytes(buf1), Bytes(buf3));
57 errno = 0;
58 uint8_t toobig[257];
59 // getentropy should fail returning -1 and setting errno to EIO if you request
60 // more than 256 bytes of entropy. macOS's man page says EIO but it actually
61 // returns EINVAL, so we accept either.
62 EXPECT_EQ(getentropy(toobig, 257), -1);
63 EXPECT_TRUE(errno == EIO || errno == EINVAL);
64}
65#endif