| 6 | // |
| 7 | // https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 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 |
| 27 | #include <errno.h> |
| 28 |
| 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 |
| 42 | TEST(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 |
| 66 |