1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/rand_util.h"
13 #include "base/check.h"
14 #include "base/compiler_specific.h"
15 #include "base/files/file_util.h"
16 #include "base/no_destructor.h"
17 #include "base/posix/eintr_wrapper.h"
18 #include "build/build_config.h"
20 #if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && !defined(OS_NACL)
21 #include "third_party/lss/linux_syscall_support.h"
23 // TODO(crbug.com/995996): Waiting for this header to appear in the iOS SDK.
25 #include <sys/random.h>
31 // AIX has no 64-bit support for O_CLOEXEC.
32 static constexpr int kOpenFlags = O_RDONLY;
34 static constexpr int kOpenFlags = O_RDONLY | O_CLOEXEC;
37 // We keep the file descriptor for /dev/urandom around so we don't need to
38 // reopen it (which is expensive), and since we may not even be able to reopen
39 // it if we are later put in a sandbox. This class wraps the file descriptor so
40 // we can use a static-local variable to handle opening it on the first access.
43 URandomFd() : fd_(HANDLE_EINTR(open("/dev/urandom", kOpenFlags))) {
44 CHECK(fd_ >= 0) << "Cannot open /dev/urandom";
47 ~URandomFd() { close(fd_); }
49 int fd() const { return fd_; }
59 // NOTE: In an ideal future, all implementations of this function will just
60 // wrap BoringSSL's `RAND_bytes`. TODO(crbug.com/995996): Figure out the
61 // build/test/performance issues with dcheng's CL
62 // (https://chromium-review.googlesource.com/c/chromium/src/+/1545096) and land
63 // it or some form of it.
64 void RandBytes(void* output, size_t output_length) {
65 #if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && !defined(OS_NACL)
66 // We have to call `getrandom` via Linux Syscall Support, rather than through
67 // the libc wrapper, because we might not have an up-to-date libc (e.g. on
69 const ssize_t r = HANDLE_EINTR(sys_getrandom(output, output_length, 0));
71 // Return success only on total success. In case errno == ENOSYS (or any other
72 // error), we'll fall through to reading from urandom below.
73 if (output_length == static_cast<size_t>(r)) {
74 MSAN_UNPOISON(output, output_length);
78 // TODO(crbug.com/995996): Enable this on iOS too, when sys/random.h arrives
80 if (__builtin_available(macOS 10.12, *)) {
81 if (getentropy(output, output_length) == 0) {
87 // If the OS-specific mechanisms didn't work, fall through to reading from
90 // TODO(crbug.com/995996): When we no longer need to support old Linux
91 // kernels, we can get rid of this /dev/urandom branch altogether.
92 const int urandom_fd = GetUrandomFD();
94 ReadFromFD(urandom_fd, static_cast<char*>(output), output_length);
99 static NoDestructor<URandomFd> urandom_fd;
100 return urandom_fd->fd();