blob: 6a6e05ada814d2758a46f82b2097016665179c67 [file] [log] [blame]
[email protected]ead8c1fa2012-05-30 14:26:131// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]05f9b682008-09-29 22:18:012// 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
[email protected]09e5f47a2009-06-26 10:00:027#include <errno.h>
[email protected]05f9b682008-09-29 22:18:018#include <fcntl.h>
avi9b6f42932015-12-26 22:15:149#include <stddef.h>
10#include <stdint.h>
[email protected]05f9b682008-09-29 22:18:0111#include <unistd.h>
12
[email protected]e3177dd52014-08-13 20:22:1413#include "base/files/file_util.h"
[email protected]09e5f47a2009-06-26 10:00:0214#include "base/lazy_instance.h"
[email protected]05f9b682008-09-29 22:18:0115#include "base/logging.h"
16
[email protected]09e5f47a2009-06-26 10:00:0217namespace {
18
19// We keep the file descriptor for /dev/urandom around so we don't need to
20// reopen it (which is expensive), and since we may not even be able to reopen
21// it if we are later put in a sandbox. This class wraps the file descriptor so
22// we can use LazyInstance to handle opening it on the first access.
23class URandomFd {
24 public:
[email protected]c910c5a2014-01-23 02:14:2825 URandomFd() : fd_(open("/dev/urandom", O_RDONLY)) {
[email protected]a42d4632011-10-26 21:48:0026 DCHECK_GE(fd_, 0) << "Cannot open /dev/urandom: " << errno;
[email protected]09e5f47a2009-06-26 10:00:0227 }
28
[email protected]c910c5a2014-01-23 02:14:2829 ~URandomFd() { close(fd_); }
[email protected]09e5f47a2009-06-26 10:00:0230
31 int fd() const { return fd_; }
32
33 private:
[email protected]c910c5a2014-01-23 02:14:2834 const int fd_;
[email protected]09e5f47a2009-06-26 10:00:0235};
36
[email protected]6ecc0962012-12-21 02:59:5037base::LazyInstance<URandomFd>::Leaky g_urandom_fd = LAZY_INSTANCE_INITIALIZER;
[email protected]09e5f47a2009-06-26 10:00:0238
39} // namespace
40
[email protected]05f9b682008-09-29 22:18:0141namespace base {
42
[email protected]9b205782012-08-02 20:22:2543// NOTE: This function must be cryptographically secure. http://crbug.com/140076
avi9b6f42932015-12-26 22:15:1444uint64_t RandUint64() {
45 uint64_t number;
[email protected]c910c5a2014-01-23 02:14:2846 RandBytes(&number, sizeof(number));
[email protected]05f9b682008-09-29 22:18:0147 return number;
48}
49
[email protected]c910c5a2014-01-23 02:14:2850void RandBytes(void* output, size_t output_length) {
51 const int urandom_fd = g_urandom_fd.Pointer()->fd();
52 const bool success =
53 ReadFromFD(urandom_fd, static_cast<char*>(output), output_length);
54 CHECK(success);
55}
56
[email protected]1d87fad2010-03-04 20:18:5557int GetUrandomFD(void) {
58 return g_urandom_fd.Pointer()->fd();
59}
[email protected]ead8c1fa2012-05-30 14:26:1360
61} // namespace base