Home | History | Annotate | Download | only in base
      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.
      4 
      5 #include "base/rand_util.h"
      6 
      7 #include <errno.h>
      8 #include <fcntl.h>
      9 #include <stddef.h>
     10 #include <stdint.h>
     11 #include <unistd.h>
     12 
     13 #include "base/files/file_util.h"
     14 #include "base/lazy_instance.h"
     15 #include "base/logging.h"
     16 #include "base/posix/eintr_wrapper.h"
     17 
     18 namespace {
     19 
     20 // We keep the file descriptor for /dev/urandom around so we don't need to
     21 // reopen it (which is expensive), and since we may not even be able to reopen
     22 // it if we are later put in a sandbox. This class wraps the file descriptor so
     23 // we can use LazyInstance to handle opening it on the first access.
     24 class URandomFd {
     25  public:
     26   URandomFd() : fd_(HANDLE_EINTR(open("/dev/urandom", O_RDONLY | O_CLOEXEC))) {
     27     DCHECK_GE(fd_, 0) << "Cannot open /dev/urandom: " << errno;
     28   }
     29 
     30   ~URandomFd() { close(fd_); }
     31 
     32   int fd() const { return fd_; }
     33 
     34  private:
     35   const int fd_;
     36 };
     37 
     38 base::LazyInstance<URandomFd>::Leaky g_urandom_fd = LAZY_INSTANCE_INITIALIZER;
     39 
     40 }  // namespace
     41 
     42 namespace base {
     43 
     44 // NOTE: This function must be cryptographically secure. http://crbug.com/140076
     45 uint64_t RandUint64() {
     46   uint64_t number;
     47   RandBytes(&number, sizeof(number));
     48   return number;
     49 }
     50 
     51 void RandBytes(void* output, size_t output_length) {
     52   const int urandom_fd = g_urandom_fd.Pointer()->fd();
     53   const bool success =
     54       ReadFromFD(urandom_fd, static_cast<char*>(output), output_length);
     55   CHECK(success);
     56 }
     57 
     58 int GetUrandomFD(void) {
     59   return g_urandom_fd.Pointer()->fd();
     60 }
     61 
     62 }  // namespace base
     63