#include <gtest/gtest.h>
#include <stdlib.h>
#include <openssl/ctrdrbg.h>
#include <openssl/rand.h>
#include "getrandom_fillin.h"
#include "internal.h"
#include "../ube/internal.h"
#include "../ube/snapsafe_detect.h"
#if defined(OPENSSL_RAND_URANDOM) && \
defined(OPENSSL_X86_64) && \
!defined(BORINGSSL_SHARED_LIBRARY) && \
!defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE) && \
defined(USE_NR_getrandom) && !defined(AWSLC_SNAPSAFE_TESTING)
#include <linux/types.h>
#include <linux/random.h>
#include <sys/ptrace.h>
#include <sys/syscall.h>
#include <sys/user.h>
#include "../ube/fork_detect.h"
#include "getrandom_fillin.h"
#include "../test/test_util.h"
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#if !defined(PTRACE_O_EXITKILL)
#define PTRACE_O_EXITKILL (1 << 20)
#endif
#if !defined(PTRACE_O_TRACESYSGOOD)
#define PTRACE_O_TRACESYSGOOD (1)
#endif
struct Event {
enum class Syscall {
kGetRandom,
kOpen,
kUrandomRead,
kUrandomIoctl,
kNanoSleep,
kAbort,
};
explicit Event(Syscall syscall) : type(syscall) {}
bool operator==(const Event &other) const {
return type == other.type && length == other.length &&
flags == other.flags && filename == other.filename;
}
static Event GetRandom(size_t length, unsigned flags) {
Event e(Syscall::kGetRandom);
e.length = length;
e.flags = flags;
return e;
}
static Event Open(std::string filename) {
Event e(Syscall::kOpen);
e.filename = std::move(filename);
return e;
}
static Event UrandomRead(size_t length) {
Event e(Syscall::kUrandomRead);
e.length = length;
return e;
}
static Event UrandomIoctl() {
Event e(Syscall::kUrandomIoctl);
return e;
}
static Event Abort() {
Event e(Syscall::kAbort);
return e;
}
static Event NanoSleep() {
Event e(Syscall::kNanoSleep);
return e;
}
std::string String() const {
char buf[256];
switch (type) {
case Syscall::kGetRandom:
snprintf(buf, sizeof(buf), "getrandom(_, %zu, %u)", length, flags);
break;
case Syscall::kOpen:
snprintf(buf, sizeof(buf), "open(%s, _)", filename.c_str());
break;
case Syscall::kUrandomRead:
snprintf(buf, sizeof(buf), "read(urandom_fd, _, %zu)", length);
break;
case Syscall::kNanoSleep:
return "nanosleep(_)";
case Syscall::kUrandomIoctl:
return "ioctl(urandom_fd, RNDGETENTCNT, _)";
case Syscall::kAbort:
return "abort()";
}
return std::string(buf);
}
const Syscall type;
size_t length = 0;
unsigned flags = 0;
std::string filename;
};
static std::string ToString(const std::vector<Event> &trace) {
std::string ret;
for (const auto &event : trace) {
if (!ret.empty()) {
ret += ", ";
}
ret += event.String();
}
return ret;
}
static const unsigned NO_GETRANDOM = 1;
static const unsigned NO_URANDOM = 2;
static const unsigned GETRANDOM_NOT_READY = 4;
static const unsigned URANDOM_NOT_READY = 8;
static const unsigned GETRANDOM_ERROR = 16;
static const unsigned URANDOM_ERROR = 32;
static const unsigned NEXT_FLAG = 64;
static std::string ReadString(pid_t pid, unsigned long addr) {
std::string result;
size_t i = 0;
while (i < 4096) { long data = ptrace(PTRACE_PEEKDATA, pid, addr + i, NULL);
if (data == -1 && errno) {
break;
}
char *p = (char*)&data;
for (size_t j = 0; j < sizeof(long); j++) {
if (p[j] == '\0') {
return result;
}
result += p[j];
}
i += sizeof(long);
}
return result;
}
static bool HasPrefix(const std::string& str, const std::string& prefix) {
return str.length() >= prefix.length() &&
(str.compare(0, prefix.length(), prefix) == 0);
}
static void GetTrace(std::vector<Event> *out_trace, unsigned flags,
std::function<void()> thunk) {
const int child_pid = fork();
ASSERT_NE(-1, child_pid);
if (child_pid == 0) {
if (ptrace(PTRACE_TRACEME, 0, 0, 0) != 0) {
perror("PTRACE_TRACEME");
_exit(1);
}
raise(SIGSTOP);
thunk();
_exit(0);
}
int status;
ASSERT_EQ(child_pid, waitpid(child_pid, &status, 0));
ASSERT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
<< "Child was not stopped with SIGSTOP: " << status;
ASSERT_EQ(0, ptrace(PTRACE_SETOPTIONS, child_pid, nullptr,
PTRACE_O_EXITKILL | PTRACE_O_TRACESYSGOOD))
<< strerror(errno);
int urandom_fd = -1;
bool urandom_not_ready_was_cleared = false;
for (;;) {
ASSERT_EQ(0, ptrace(PTRACE_SYSCALL, child_pid, 0, 0));
ASSERT_EQ(child_pid, waitpid(child_pid, &status, 0));
if (WIFSTOPPED(status) && WSTOPSIG(status) == SIGABRT) {
out_trace->push_back(Event::Abort());
break;
}
ASSERT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == (SIGTRAP | 0x80))
<< "Child was not stopped with a syscall stop: " << status;
struct user_regs_struct regs;
ASSERT_EQ(0, ptrace(PTRACE_GETREGS, child_pid, nullptr, ®s));
const auto syscall_number = regs.orig_rax;
static auto previous_syscall = regs.orig_rax;
bool is_opening_urandom = false;
bool is_urandom_ioctl = false;
uintptr_t ioctl_output_addr = 0;
int inject_error = 0;
switch (syscall_number) {
case __NR_getrandom:
if (flags & NO_GETRANDOM) {
inject_error = -ENOSYS;
} else if (flags & GETRANDOM_ERROR) {
inject_error = -EINVAL;
} else if (flags & GETRANDOM_NOT_READY) {
if (regs.rdx & GRND_NONBLOCK) {
inject_error = -EAGAIN;
}
}
out_trace->push_back(
Event::GetRandom(regs.rsi, regs.rdx));
break;
case __NR_openat:
case __NR_open: {
std::string filename = ReadString(child_pid,
(syscall_number == __NR_openat) ? regs.rsi : regs.rdi);
if (HasPrefix(filename, "/sys/devices/system/cpu/cpu0/cache")) {
break;
}
if (filename != CRYPTO_get_sysgenid_path()) {
out_trace->push_back(Event::Open(filename));
}
is_opening_urandom = (filename == "/dev/urandom");
if (is_opening_urandom && (flags & NO_URANDOM)) {
inject_error = -ENOENT;
}
break;
}
case __NR_read: {
const int read_fd = regs.rdi;
if (urandom_fd >= 0 && urandom_fd == read_fd) {
out_trace->push_back(Event::UrandomRead(regs.rdx));
if (flags & URANDOM_ERROR) {
inject_error = -EINVAL;
}
}
break;
}
case __NR_nanosleep: {
if (urandom_not_ready_was_cleared ||
((flags & URANDOM_ERROR) && (previous_syscall != __NR_nanosleep))) {
out_trace->push_back(Event::NanoSleep());
}
break;
}
case __NR_clock_nanosleep: {
if (urandom_not_ready_was_cleared ||
((flags & URANDOM_ERROR) &&
(previous_syscall != __NR_clock_nanosleep))) {
out_trace->push_back(Event::NanoSleep());
}
break;
}
case __NR_ioctl: {
const int ioctl_fd = regs.rdi;
if (urandom_fd >= 0 && ioctl_fd == urandom_fd &&
(regs.rsi & 0xFFFFFFFF) == RNDGETENTCNT) {
out_trace->push_back(Event::UrandomIoctl());
is_urandom_ioctl = true;
ioctl_output_addr = regs.rdx;
}
}
}
previous_syscall = syscall_number;
if (inject_error) {
regs.orig_rax = -1;
ASSERT_EQ(0, ptrace(PTRACE_SETREGS, child_pid, nullptr, ®s));
}
ASSERT_EQ(0, ptrace(PTRACE_SYSCALL, child_pid, 0, 0));
ASSERT_EQ(child_pid, waitpid(child_pid, &status, 0));
if (WIFEXITED(status)) {
ASSERT_EQ(0, WEXITSTATUS(status));
return;
}
ASSERT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == (SIGTRAP | 0x80));
if (inject_error) {
if (inject_error != -ENOSYS) {
ASSERT_EQ(0, ptrace(PTRACE_GETREGS, child_pid, nullptr, ®s));
regs.rax = inject_error;
ASSERT_EQ(0, ptrace(PTRACE_SETREGS, child_pid, nullptr, ®s));
}
} else if (is_opening_urandom) {
ASSERT_EQ(0, ptrace(PTRACE_GETREGS, child_pid, nullptr, ®s));
urandom_fd = regs.rax;
} else if (is_urandom_ioctl) {
int result = 256;
if (flags & URANDOM_NOT_READY) {
result--;
flags &= ~URANDOM_NOT_READY;
urandom_not_ready_was_cleared = true;
}
const uintptr_t aligned_addr = ioctl_output_addr & ~7;
const uintptr_t offset = ioctl_output_addr - aligned_addr;
union {
uint64_t word;
uint8_t bytes[8];
} u;
u.word = ptrace(PTRACE_PEEKDATA, child_pid,
reinterpret_cast<void *>(aligned_addr), nullptr);
memcpy(&u.bytes[offset], &result, sizeof(result));
ASSERT_EQ(0, ptrace(PTRACE_POKEDATA, child_pid,
reinterpret_cast<void *>(aligned_addr),
reinterpret_cast<void *>(u.word)));
}
}
}
static void TestFunction() {
uint8_t byte;
RAND_bytes(&byte, sizeof(byte));
RAND_bytes(&byte, sizeof(byte));
}
static bool have_ube_detection() {
uint64_t tmp_gn = 0;
return CRYPTO_get_ube_generation_number(&tmp_gn) != 0;
}
static std::vector<Event> TestFunctionPRNGModel(unsigned flags) {
std::vector<Event> ret;
bool urandom_ready = false;
bool getrandom_ready = false;
ret.push_back(Event::GetRandom(1, GRND_NONBLOCK));
std::function<void()> ensure_entropy_pool_is_initialized;
std::function<bool(bool, size_t)> sysrand;
if (flags & NO_GETRANDOM) {
ret.push_back(Event::Open(std::string("/dev/urandom")));
if (flags & NO_URANDOM) {
ret.push_back(Event::Abort());
return ret;
}
ensure_entropy_pool_is_initialized = [&ret, &urandom_ready, flags] {
if (urandom_ready) {
return;
}
ret.push_back(Event::UrandomIoctl());
if (flags & URANDOM_NOT_READY) {
ret.push_back(Event::NanoSleep());
ret.push_back(Event::UrandomIoctl());
}
urandom_ready = true;
};
sysrand = [&ret, &ensure_entropy_pool_is_initialized, flags](bool block, size_t len) {
if (block) {
ensure_entropy_pool_is_initialized();
}
ret.push_back(Event::UrandomRead(len));
if (flags & URANDOM_ERROR) {
if (block) {
for (size_t i = 0; i < MAX_BACKOFF_RETRIES; i++) {
ret.push_back(Event::NanoSleep());
ret.push_back(Event::UrandomRead(len));
}
}
ret.push_back(Event::Abort());
return false;
}
return true;
};
} else {
if (flags & GETRANDOM_ERROR) {
ret.push_back(Event::Abort());
return ret;
}
getrandom_ready = (flags & GETRANDOM_NOT_READY) == 0;
ensure_entropy_pool_is_initialized = [&ret, &getrandom_ready] {
if (getrandom_ready) {
return;
}
ret.push_back(Event::GetRandom(1, GRND_NONBLOCK));
ret.push_back(Event::GetRandom(1, 0));
getrandom_ready = true;
};
sysrand = [&ret, &ensure_entropy_pool_is_initialized](bool block, size_t len) {
if (block) {
ensure_entropy_pool_is_initialized();
}
ret.push_back(Event::GetRandom(len, block ? 0 : GRND_NONBLOCK));
return true;
};
}
const size_t kPersonalizationStringLength = CTR_DRBG_ENTROPY_LEN;
const size_t kPredictionResistanceStringLength = RAND_PRED_RESISTANCE_LEN;
const bool kHaveUbeDetection = have_ube_detection();
if (!kHaveUbeDetection) {
if (!sysrand(true, kPredictionResistanceStringLength)) {
return ret;
}
}
if (!sysrand(true, kPersonalizationStringLength)) {
return ret;
}
if (!kHaveUbeDetection) {
if (!kHaveUbeDetection) {
if (!sysrand(true, kPredictionResistanceStringLength)) {
return ret;
}
}
if (!sysrand(true, kPersonalizationStringLength)) {
return ret;
}
}
return ret;
}
#define SCOPED_TRACE_FLAG(flag) \
snprintf(buf, sizeof(buf), #flag ": %d", (flags & flag) != 0); \
SCOPED_TRACE(buf);
TEST(URandomTest, Test) {
char buf[256];
uint8_t scratch[1];
const bool has_getrandom =
(syscall(__NR_getrandom, scratch, sizeof(scratch), GRND_NONBLOCK) != -1 ||
errno != ENOSYS);
for (unsigned flags = 0; flags < NEXT_FLAG; flags++) {
if (!has_getrandom && !(flags & NO_GETRANDOM)) {
continue;
}
SCOPED_TRACE_FLAG(NO_GETRANDOM);
SCOPED_TRACE_FLAG(NO_URANDOM);
SCOPED_TRACE_FLAG(GETRANDOM_NOT_READY);
SCOPED_TRACE_FLAG(URANDOM_NOT_READY);
SCOPED_TRACE_FLAG(GETRANDOM_ERROR);
SCOPED_TRACE_FLAG(URANDOM_ERROR);
const std::vector<Event> expected_trace = TestFunctionPRNGModel(flags);
std::vector<Event> actual_trace;
GetTrace(&actual_trace, flags, TestFunction);
if (expected_trace != actual_trace) {
ADD_FAILURE() << "Expected: " << ToString(expected_trace)
<< "\nFound: " << ToString(actual_trace);
}
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
maybeDisableSomeForkDetectMechanisms();
return RUN_ALL_TESTS();
}
#else
int main(int argc, char **argv) {
printf("PASS\n");
return 0;
}
#endif